Reputation: 1019
I have two arrays as follows
const arr1 = ['john', 'robot'];
const arr2 = [{name : 'john'}, {name : 'kevin'}, {name : 'james}];
My desired output is to manipulate array arr1 such that if value of arr1 is not present as a name property in arr2 it should get removed from arr1;
So in the above example after the operation, the output should be
console.log(arr1) // ['john']
as robot is not present in arr2, it gets removed.
Likewise if I have following set of arrays
const names = ['sachin', 'sehwag'];
const players = [{name : 'dhoni'}, {name : 'dravid'}, {name : 'ganguly'} , {name : 'laxman}];
names array should be manipulated to
console.log(names) // []
as both sachin and sehwag is not present in players array
Please help.Thanks in advance.
Upvotes: 0
Views: 51
Reputation: 92440
If you can use es6, a Set is good for this. They only store unique values and are efficient at lookup. They give constant time lookups, which looping through an array doesn't:
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)
Upvotes: 3
Reputation: 6426
This sounds like a job for [].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;
});
}
Upvotes: -1
Reputation: 118261
You can first grab all the names from array of objects arr2
, and then filter the arr1
based on names
list..
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)));
Upvotes: 2
Reputation: 3386
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);
Hope it helps you!
Upvotes: 1