I have an array of objects, I want to assign a random color to each element if elements have the same id in javascript.
what I have
[
{id:1,
value: 'test',
},
{id:1,
value: 'test',
},
{id:2,
value: 'test',
}
,{id:3,
value: 'test',
}
]
What I want
[
{id:1,
value: 'test',
color: 'green'
},
{id:1,
value: 'test',
color: 'green'
},
{id:2,
value: 'test',
color: 'blue'
}
,{id:3,
value: 'test',
color:'red'
}
]
I know we can use below code to set random color:
var colors = ['red', 'green', 'blue', 'orange', 'yellow'];
data = colors[Math.floor(Math.random() * colors.length)];
2
Answers
Have you tried having an object or the map data structure to keep the pairs of ID and color? You can use array
forEach
ormap
methods to iterate and assign corresponding values.You have to keep track of what color you assigned to which ID. This can be done using a seperate object which gets assigned an
id
:color
pair for every new ID.All that is left is to iterate over your array of objects and add the color value to every object: