0

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' }

]
1
  • 1
    What should the result be if brands is ['XM5', 'XM6']? Commented Aug 30, 2022 at 14:40

2 Answers 2

1

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);

Sign up to request clarification or add additional context in comments.

Comments

1

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.