0

I have an array of arrays which I want to marge into one and remove duplicate values.

let arr = [ {
  label :'XYZ',
  colors:['black','white','blue']
},
{
  label :'PQR',
  colors:['orange','yellow','white']
},

{
  label :'ABC',
  colors:['black','pink','blue']
},
]

let updatedArr = []


for(let i=0 i< arr.length ; i++ ){
  updatedArr.push(
                arr[i].reduce((a, b) => [...a, ...b], [])
            )

}

I want all the colors array value into one array and remove duplicate values as well.

Any help would be great.

3 Answers 3

1

To get a concatenated list of all values you can use flatMap(). And to deduplicate you can use [...new Set(duplicates)], which creates a Set of unique elements and spreads it into an array.

let arr = [{
    label: 'XYZ',
    colors: ['black', 'white', 'blue']
  },
  {
    label: 'PQR',
    colors: ['orange', 'yellow', 'white']
  },

  {
    label: 'ABC',
    colors: ['black', 'pink', 'blue']
  },
]

let colors = [...new Set(arr.flatMap(obj => obj.colors))]
console.log(colors)

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

Comments

0

You can use reduce and forEach. Inside reduce call back use forEach to iterate the colors array & if accumulator does not include the color then push that color to accumulator

let arr = [{
    label: 'XYZ',
    colors: ['black', 'white', 'blue']
  },
  {
    label: 'PQR',
    colors: ['orange', 'yellow', 'white']
  },

  {
    label: 'ABC',
    colors: ['black', 'pink', 'blue']
  },
]


let mergedColor = arr.reduce((acc, curr) => {
  curr.colors.forEach((item) => {
    if (acc.indexOf(item) === -1) {
      acc.push(item)
    }
  })

  return acc;
}, []);

console.log(mergedColor)

Comments

0

Use Array.prototype.flat for flatting the array, and then use a Set for distincting values and then create an array from the set using the Spread operator.

let arr = [{
    label: 'XYZ',
    colors: ['black', 'white', 'blue']
  },
  {
    label: 'PQR',
    colors: ['orange', 'yellow', 'white']
  },

  {
    label: 'ABC',
    colors: ['black', 'pink', 'blue']
  },
]

const vals = [...new Set(arr.map(i => i.colors).flat())]

console.log(vals)

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.