2

I'm writing a code where I need to return uniques values from a JSON array. Here my challenge is, I've got these values as an array for one of the keys.

Here is my code.

let mobilePhones = [{
  id: 1,
  brand: ["B1", "B2"]
}, {
  id: 2,
  brand: ["B2"]
}, {
  id: 3,
  brand: ["B1", "B2"]
}, {
  id: 4,
  brand: ["B1"]
}, {
  id: 5,
  brand: ["B2", "B1"]
}, {
  id: 6,
  brand: ["B3"]
}]
let allBrandsArr = mobilePhones.map(row => {
  return row.brand;
});
let uniqueBrands = allBrandsArr.filter((item, index, arry) => (arry.indexOf(item) === index));
console.log(JSON.stringify(uniqueBrands));

Here my expected result is to get ["B1", "B2", "B3"]. Please let me know how can I achieve this.

Updated new sample data:

let mobilePhones = [{
      id: 1,
      brand: ["B1, B2"]
    }, {
      id: 2,
      brand: ["B2"]
    }, {
      id: 3,
      brand: ["B1, B2"]
    }, {
      id: 4,
      brand: ["B1"]
    }, {
      id: 5,
      brand: ["B2, B1"]
    }, {
      id: 6,
      brand: ["B3"]
    }]
    let allBrandsArr = mobilePhones.map(row => {
      return row.brand;
    });

Thanks

2 Answers 2

2

You need to use flat for merge sub array then your code was good:

let mobilePhones = [{
  id: 1,
  brand: ["B1, B2"]
}, {
  id: 2,
  brand: ["B2"]
}, {
  id: 3,
  brand: ["B1, B2"]
}, {
  id: 4,
  brand: ["B1"]
}, {
  id: 5,
  brand: ["B2, B1"]
}, {
  id: 6,
  brand: ["B3"]
}]
let allBrandsArr = mobilePhones.map(row => {
  return row.brand[0].split(',').map(function(item) {
    return item.trim();
  });
});
let uniqueBrands = allBrandsArr.flat().filter((item, index, arry) => (arry.indexOf(item) === index));
console.log(JSON.stringify(uniqueBrands));

Reference:


After new Data posted i add split with trim.

Reference:

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

2 Comments

Thanks for this Simone. I've seen another pattern in my data it is like ["B1, B2"] and also ["B1", "B2"]. How can I handle these cases? I just updated my question.
I add support for new data.
0

You can use .flatMap to get all the brand values and pass it to a Set to make it unique.

const uniqueBrands = [...new Set(mobilePhones.flatMap(({
  brand
}) => brand))];

let mobilePhones = [{
  id: 1,
  brand: ["B1", "B2"]
}, {
  id: 2,
  brand: ["B2"]
}, {
  id: 3,
  brand: ["B1", "B2"]
}, {
  id: 4,
  brand: ["B1"]
}, {
  id: 5,
  brand: ["B2", "B1"]
}, {
  id: 6,
  brand: ["B3"]
}]

const unique = [...new Set(mobilePhones.flatMap(({
  brand
}) => brand))];

console.log(unique);

1 Comment

Thanks, Gabriele for this. I have a case where I can have data in both formats ["B1, B2"] or ["B1", "B2"]. How can I handle them? Updated my question

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.