-1

I have two arrays. The first array has only id objects:

arr1 = [
  { id: 1 },
  { id: 2 }
];

and another array has list:

arr2 = [
  { id: 1, name: "kedar" },
  { id: 2, name: "murli" },
  { id: 3, name: "krishnadas" }
];

I need to write arr2 filter function which result as, based on ID available in first array

arr2 = [
  { id: 1, name: "kedar" },
  { id: 2, name: "murli" }
];
Jason Aller
  • 3,541
  • 28
  • 38
  • 38
  • 1
    Does this answer your question? [How to filter an array from all elements of another array](https://stackoverflow.com/questions/34901593/how-to-filter-an-array-from-all-elements-of-another-array) – chiliNUT Feb 18 '20 at 14:49

4 Answers4

2

const needle = [{
    id: 1
  },
  {
    id: 2
  }
];

const haystack = [{
  id: 1,
  name: 'kedar'
}, {
  id: 2,
  name: 'murli'
}, {
  id: 3,
  name: 'krishnadas'
}];


const filterByIdArray = (ids, arr) =>
  arr.filter(item =>
    ids.find(i =>
      i.id === item.id));

const result = filterByIdArray(needle, haystack);

console.log(result);
karlmarxlopez
  • 1,019
  • 1
  • 8
  • 16
0

You can create a string using the id value from the first array. So the string will be 1 2, then use filter to create an array of elements from second array and for elements where the id value is included in the string

let arr1 = [{
  id: 1
}, {
  id: 2
}];
let arr2 = [{
  id: 1,
  name: 'kedar'
}, {
  id: 2,
  name: 'murli'
}, {
  id: 3,
  name: 'krishnadas'
}];

let str = arr1.reduce((acc, curr) => {
  acc += ' ' + curr.id

  return acc.trim();
}, '');

let newArr = arr2.filter((item) => {
  // check if id value is included in the string
  return str.indexOf(item.id) != -1;
});

console.log(newArr)
brk
  • 48,835
  • 10
  • 56
  • 78
0

let a1 = [ {id:1}, {id:2}]
let b1 = [ {id:1, name:'kedar'}, {id:2, name:'murli'}, {id:3, name:'kidu'} ]

let filteredArray = b1.filter(elem => {
      let id_exists = a1.find(id => { return elem.id === id.id });
      return id_exists;
    });
    
console.log(filteredArray);
Mohammad Faisal
  • 2,144
  • 15
  • 26
diffuse
  • 620
  • 1
  • 7
  • 15
0
arr2.filter(el2 => arr1.some(el1 => el1.id === el2.id))
chiliNUT
  • 18,989
  • 14
  • 66
  • 106
  • 4
    While this code may provide a solution to OP's problem, it is highly recommended that you provide additional context regarding why and/or how this code answers the question. Code only answers typically become useless in the long-run because future viewers experiencing similar problems cannot understand the reasoning behind the solution. – E. Zeytinci Feb 18 '20 at 13:36