Get unique values from array values in json array

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

>Solution :

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:

Leave a Reply