遍历两个数组并使用javascript获取所需的输出

时间:2018-08-19 16:28:31

标签: javascript

我有以下两个数组

functionList['row_rendering_function_name'] = (row) => { 
   return (<span>{`${date(row.createdAt)}`}</span>) 
}

我想要的输出是操纵数组arr1,以便如果arr1的值不作为arr2中的name属性出现,则应将其从arr1中删除;

因此在上面的示例中,操作之后,输出应为

const arr1 = ['john', 'robot'];

const arr2 = [{name : 'john'}, {name : 'kevin'}, {name : 'james}];

由于arr2中不存在机械手,因此将其删除。

同样,如果我有以下一组数组

console.log(arr1)  // ['john']

names数组应操作为

const names = ['sachin', 'sehwag'];

const players = [{name : 'dhoni'}, {name : 'dravid'}, {name : 'ganguly'} , {name : 'laxman}];

因为sachin和sehwag都不存在于玩家数组中

请帮助。谢谢。

4 个答案:

答案 0 :(得分:3)

如果可以使用es6,则Set对此很有用。它们仅存储唯一值,并且查找效率很高。它们提供恒定的时间查找,而循环遍历数组则不会:

const arr1 = ['john', 'robot'];
const arr2 = [{name : 'john'}, {name : 'kevin'}, {name : 'james'}];

// create a set with names
let testSet = arr2.reduce((set, obj) => set.add(obj.name), new Set)

let filtered = arr1.filter(item => testSet.has(item))
console.log(filtered)

答案 1 :(得分:2)

您可以首先从对象arr2的数组中获取所有名称,然后根据arr1列表过滤names

var arr1 = ["john", "robot"];
var arr2 = [{ name: "john" }, { name: "kevin" }, { name: "james" }];
var names = arr2.map(ob => ob.name);
console.log(arr1.filter(name => names.includes(name)));

var arr1 = ["sachin", "sehwag"];
var arr2 = [
  { name: "dhoni" },
  { name: "dravid" },
  { name: "ganguly" },
  { name: "laxman" }
];
var names = arr2.map(ob => ob.name);
console.log(arr1.filter(name => names.includes(name)));

答案 2 :(得分:1)

       const arr1 = ['john', 'robot'];
       const arr2 = [{name : 'john'}, {name : 'kevin'}, {name : 'james'}];
        var newArray= [];
        for(var i in arr2) {
            var content = arr2[i]['name'];
              if(arr1.indexOf(content) > -1){
                   newArray.push(content);
                }
        }

    console.log(newArray);

希望对您有帮助!

答案 3 :(得分:-1)

这听起来像是[].filter的工作:

function doTheThingYouWantItToDo(a, b) {
    return a.filter(function(elem) {
        for (var i = 0; i < b.length; i+=1) {
            if (b[i].name == elem) {
                return true;
            }
        }
        return false;
    });
}