i have the following array of objects:
[
{ ip: 1, name: 'examplel' },
{ ip: 1, name: 'examplel' },
{ ip: 202.164.171.184, name: 'example2' },
{ ip: 202.164.171.184, name: 'example2' },
{ ip: 202.164.171.184, name: 'example3' },
{ ip: 127.0.0.1, name: 'example4' },
{ ip: 127.0.0.1, name: 'example5' }
]
and i want to put colors on them if they have the same ip but not equal name, so something like this.
[
{ ip: 1, name: 'examplel', color: '' },
{ ip: 1, name: 'examplel', color: '' },
{ ip: 202.164.171.184, name: 'example2', color: 'red' },
{ ip: 202.164.171.184, name: 'example2', color: 'red' },
{ ip: 202.164.171.184, name: 'example3', color: 'red' },
{ ip: 127.0.0.1, name: 'example4', color: 'black' },
{ ip: 127.0.0.1, name: 'example5', color: 'black' }
]
how can you achieve this using lodash? or vanilla?
edit: i tried to code it, but it producing different output.
[
{ ip: 1, name: 'examplel', color: 'red' },
{ ip: 1, name: 'examplel', color: 'red' },
{ ip: 202.164.171.184, name: 'example2', color: 'red' },
{ ip: 202.164.171.184, name: 'example2', color: 'red' },
{ ip: 202.164.171.184, name: 'example3', color: 'red' },
{ ip: 127.0.0.1, name: 'example4', color: 'black' },
{ ip: 127.0.0.1, name: 'example5', color: 'black' }
]
here's my code.
let list = _.groupBy(data, 'ip')
const colorList = ['pink', 'blue', 'pink', 'red']
let logsList = []
_.keys(list).forEach(key => {
const color = colorList[Math.floor(Math.random() * colorList.length)]
if (Array.isArray(list[key])) {
list[key].forEach(data => {
data.color = color
logsList.push(data)
})
}
})
Array.isArray(list[key])<= this check shouldn't be necessary. The result of a groupBy should always result in each key pointing to an array of elements, even if there is just one element.