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

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.

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

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:

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