Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Javascript: filter object by array

I want to filter an array of object by passing array elements.

var filterNumbers = [2, 4];

var obj = [
  {value: 1, lang: 'South'},
  {value: 2, lang: 'North'},
  {value: 3, lang: 'East'},
  {value: 4, lang: 'Test1'},
  {value: 5, lang: 'Test2'},
  {value: 6, lang: 'Test3'},
  ];

let myArray = [];
  for (let i = 0; i < obj.length; i++) {
    if (obj[i].value === filterNumbers[i]) {
        myArray.push(obj[i]);
    }
}

console.log(myArray);

I see my result is showing [], but instead I want something like the below:

[
  {value: 2, lang: 'North'},
  {value: 4, lang: 'Test1'}
];

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

the complete answer, idem to the comment of Andy Ray

var filterNumbers = [2, 4];

var obj = [
  {value: 1, lang: 'South'},
  {value: 2, lang: 'North'},
  {value: 3, lang: 'East'},
  {value: 4, lang: 'Test1'},
  {value: 5, lang: 'Test2'},
  {value: 6, lang: 'Test3'},
  ];

let myArray = obj.filter(({value})=>filterNumbers.includes(value)) 

console.log(myArray);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading