Sathya Sathya - 1 month ago 8
React JSX Question

How to filter array of objects by values in javascript?

So, i'm having the filtered ids in one array and having the all data's in another array of objects. I want to display filtered ids values mentioned in array of value.

var allData = [
{
id:'10',
name:'jhon'
},
{
id:'11',
name:'lewis'
},
{
id:'12',
name:'taylor'
},
{
id:'13',
name:'adam'
},
{
id:'14',
name:'bolive'
}
];

var addedIds = ['10', '12', '14'];


My javascript code,

allData.filter(data, function (item) {
item.map(function(list, i) {
if (list.id.indexOf(addedIds[i]) === -1) {
return;
}
console.log(list);
});
});

Answer

var allData = [
    {
      id:'10',
      name:'jhon'
    },
    {
      id:'11',
      name:'lewis'
    },
    {
      id:'12',
      name:'taylor'
    },
    {
      id:'13',
      name:'adam'
    },
    {
      id:'14',
      name:'bolive'
    }
];

var addedIds = ['10', '12', '14'];

var allData = allData.filter(function (item) {   
    if (addedIds.indexOf(item.id) !== -1) return item;
});

console.log(allData);

Comments