0

I have an array:

animals = [
 {name:"Dog", color_id:1, color:"Red" ....},
 {name:"Cat", color_id:2, color: "Blue"....}, 
 {name:"Fish", color_id:3, color:"Purple"...}, 
 {name:Mouse, color_id:2, color:"Blue" ...}
]

I need to return a list with unique colors:

colorList = [{value:1, label:"Red"}, {value:2, color:"Blue"}, {value:3, color:"Purple"}] 

I do this but it doesn't return the unique ids

animals.forEach(function(currAnimal){
      var i = propertyTypeOptions.findIndex(animals => animals.value == colorList.value);
      if(i <= -1){

        propertyTypeOptions.push({value: currAnimal.color_id, label:  currAnimal.color});
      }
    })
0

2 Answers 2

2

Because it looks like each color maps one-to-one onto a color_id, keep a set of the colors seen so far in a Set, and only add items if they haven't been seen yet:

const animals = [
 {name:"Dog", color_id:1, color:"Red" },
 {name:"Cat", color_id:2, color: "Blue"}, 
 {name:"Fish", color_id:3, color:"Purple"}, 
 {name:'Mouse', color_id:2, color:"Blue" }
];
const seenColors = new Set();

const output = animals.reduce((a, { color_id, color }) => {
  if (!seenColors.has(color)) {
    a.push({ color_id, color });
    seenColors.add(color);
  }
  return a;
}, []);

console.log(output);

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

1 Comment

I liked the approach you used here. It will also preserve the order of objects as in original array.
1

One option is using reduce to summarize the array into an object. Use Object.values to convert the object into an array.

let animals = [{"name":"Dog","color_id":1,"color":"Red"},{"name":"Cat","color_id":2,"color":"Blue"},{"name":"Fish","color_id":3,"color":"Purple"},{"name":"Mouse","color_id":2,"color":"Blue"}]

let colorList = Object.values(animals.reduce((c, {color,color_id}) => {
  if (!c[color]) c[color] = {label: color,value: color_id};
  return c;
}, {}));

console.log(colorList);

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.