Home > Software engineering >  filter array of objects by comparing string property with another array elements
filter array of objects by comparing string property with another array elements

Time:08-31

Suppose I have array of objects as rows below and wantedBrands is a array of strings.

let rows = [
            { name: "Russia", brands: ['XM1', 'XM2', 'XM3'] },
            { name: "Italy", brands: ['XM4', 'XM5', 'XM6'] }
           ];

let wantedBrands = ['XM5'];

let result = rows.filter(row => row.brands.some(b => wantedBands.includes(b)));
            
console.log(result);

I get result as follows because it checks which row elements has wantedBrands in it and filters accordingly

[
    { "name": "Italy", "brands": [ "XM4", "XM5", "XM6" ] }
]

Here is my problem. So instead of brands property in the array of objects being an array of strings, it will just be a single brand with one string element.

let rows = [
            { name: "Russia", brands: 'XM1' },
            { name: "Italy", brands: 'XM5' },
            { name: "Turkey", brands: 'XM5' }
];

I want result as follows. how do I achieve this result

[
    { name: "Italy", brands: 'XM5' },
    { name: "Turkey", brands: 'XM5' }

]

CodePudding user response:

Here you go :

let rows = [
  { name: "Russia", brands: 'XM1' },
  { name: "Italy", brands: 'XM5' },
  { name: "Turkey", brands: 'XM5' }
];

let wantedBrands = ['XM5'];

const res = rows.filter(({ brands }) => wantedBrands.includes(brands));

console.log(res);

CodePudding user response:

For each row check if wantedBrands includes the brand

const rows = [{
    name: "Russia",
    brands: 'XM1'
  },
  {
    name: "Italy",
    brands: 'XM5'
  },
  {
    name: "Turkey",
    brands: 'XM5'
  }
];

const wantedBrands = ['XM5'];

const result = rows.filter(row => wantedBrands.includes(row.brands));

console.log(result);

  • Related