skip to Main Content

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


  1. Have you tried having an object or the map data structure to keep the pairs of ID and color? You can use array forEach or map methods to iterate and assign corresponding values.

    Login or Signup to reply.
  2. 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:

    const objects = [
      { id: 1, name: "object1" },
      { id: 2, name: "object2" },
      { id: 3, name: "object3" },
      { id: 1, name: "object4" },
      { id: 2, name: "object5" },
      { id: 4, name: "object6" },
    ];
    
    const colors = {};
    
    objects.forEach((object) => {
      if (colors[object.id]) {
        object.color = colors[object.id];
      } else {
        const color = '#' + ('00000' + (Math.random() * 0xFFFFFF << 0).toString(16)).slice(-6);
        object.color = color;
        colors[object.id] = color;
      }
    });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search