Filter Array of Objects Based on Another Array in JavaScript

How to filter an array from all elements of another array

You can use the this parameter of the filter() function to avoid to store your filter array in a global variable.

var filtered = [1, 2, 3, 4].filter(

function(e) {

return this.indexOf(e) < 0;

},

[2, 4]

);

console.log(filtered);

Filter array of objects with another array of objects

var filtered = [];

for(var arr in myArray){
for(var filter in myFilter){
if(myArray[arr].userid == myFilter[filter].userid && myArray[arr].projectid == myFilter[filter].projectid){
filtered.push(myArray[arr].userid);
}
}
}
console.log(filtered);

Filter Array with objects based on another array dynamically

This should work

let codes = [{
"title": "lore",
"city": "New York",
"desc": "lorem lorem",
"age": "20"
},
{
"title": "lore2 ",
"city": "Santa Monica",
"desc": "lorem2",
"age": "20"
}
];

let filter = [{
"city": "New York"
}, {
"age": "20"
}];

let res = codes.filter(code => {
return filter.every(f => {
const [key, value] = Object.entries(f)[0];
return code[key] == value
});
});

console.log(res)

filter array of objects by another array of objects

Like Felix mentioned, Array#filter won't work faster than native for loop, however if you really want it as functional way, here's one possible solution:

const array = [

{ id: 1, name: 'a1', sub: { id: 6, name: 'a1 sub' } },

{ id: 2, name: 'a2', sub: null },

{ id: 3, name: 'a3', sub: { id: 8, name: 'a3 sub' } },

{ id: 4, name: 'a4', sub: null },

{ id: 5, name: 'a5', sub: { id: 10, name: 'a5 sub' } },

];

const anotherArray = [

{ id: 1, name: 'a1', sub: { id: 6, name: 'a1 sub' } },

{ id: 2, name: 'a2', sub: null },

{ id: 5, name: 'a5', sub: { id: 10, name: 'a5 sub' } },

];

const r = array.filter((elem) => !anotherArray.find(({ id }) => elem.id === id) && elem.sub);

console.log(r);

How to filter an array of objects based on another array of object's property value?

let arr1 = [
{ key: "WIHUGDYVWJ", className: "science" },
{ key: "qwljdhkuqwdnqwdk", className: "english" },
{ key: "likubqwd", className: "robotics" },
{ key: "abcd", className: "history" }
];

let arr2 = [
{ key: "WIHUGDYVWJ", title: "math" },
{ key: "qwljdhkuqwdnqwdk", title: "english" },
{ key: "likubqwd", title: "robotics" }
];

// q1 answer
console.log(arr1.map(arr1Item => arr2.filter(arr2Item => arr1Item.className === arr2Item.title)).flat());

// q2 answer
console.log(arr1.filter(arr1Item => !arr2.some(arr2Item => arr2Item.title === arr1Item.className)));


Related Topics



Leave a reply



Submit