Home > Blockchain >  Get unique array of certain column of object array in javascript
Get unique array of certain column of object array in javascript

Time:09-29

I've searched and read many related questions here but I still can't figure it out.

I have a array of objects like:

 
{id: 1, size: 'small', weight: '1 kg', color: 'red', price: 100}
{id: 2, size: 'small', weight: '1 kg', color: 'blue', price: 200}
{id: 3, size: 'small', weight: '2 kg', color: 'green', price: 300}
{id: 4, size: 'small', weight: '2 kg', color: 'yellow', price: 400}
{id: 5, size: 'large', weight: '4 kg', color: 'pink', price: 500}
{id: 6, size: 'large', weight: '4 kg', color: 'navy blue', price: 600}
{id: 7, size: 'large', weight: '4 kg', color: 'cyan', price: 700}
{id: 8, size: 'large', weight: '6 kg', color: 'amber', price: 800}
{id: 9, size: 'large', weight: '6 kg', color: 'black', price: 900}

How can I get unique values of certain column?

for example for 'size' how can I get only 'small' and 'large' from this array? Not 4 'small' and 5 'large'

Is there a way to chain it after filtering below?

products.filter((p) => Object.keys(selected).every((k) => selected[k] === p[k]))

Thanks in advance

CodePudding user response:

Use Set to reduce to unique values:

const sizeList = [ ...new Set(array.map(item => item.size)) ]
  • Related