I am traversing an object that has an array of objects inside a property and I must access the id of an object to check which colors of my objects have the same id and make an array of the different colors of the same id to display it in the frontend as a concatenated. I hope you can help me.
Here I leave the image of the object on which I am getting the ids and colors
The dm_id are the ones I need to be able to make the color_bom_header array with the same dm_id
Here is the code that makes this happen but it doesn't work right :(
this.state.stylesArray = this.props.location.state.stylesCombo.components.map((index, current) => {
const col = this.state.stylesCombo.components && (this.state.stylesCombo.components[current].style_colors = index.color_bom_name)
if(this.state.stylesCombo.components && this.state.stylesCombo.components[current].dm_id === index.dm_id){
if(this.state.stylesCombo.components[current].dm_name === index.dm_name){
this.state.colorStArray.push(col)
this.state.cstarr = [...new Set(this.state.colorStArray)]
}
}else{
this.state.stylesCombo.components && (this.state.stylesCombo.components[current].style_colors = current.color_bom_name)
}
this.state.stylesCombo.components && (this.state.stylesCombo.components[current].style_colors = this.state.cstarr)
})
i have also tried with this but im stuck
this.state.stylesArray = this.props.location.state.stylesCombo.components.map((current, index) => {
for (current.dm_id in this.props.location.state.stylesCombo && this.props.location.state.stylesCombo.components) {
if(current.dm_id === index.dm_id){
}else{
}
}
this.state.stylesCombo.components && (this.state.stylesCombo.components[index].style_colors = this.state.colorStArray)
})
So the task is to make an array of elements with the same ID.
We need to somehow count how many elements of each ID are presented. We can do that with an object.
const counter = {}
for (const el of arr) {
// if counter has element with given ID, increase the counter, otherwise initialize to 1
counter[el.id] = (counter[el.id] || 0) + 1;
}
Then we find ID that have the max count
const max = Object.entries(counter).reduce((acc, curr) => {
if (acc.length === 0) return curr;
const [currKey, currVal] = curr;
const [maxKey, maxVal] = acc;
return currVal > maxVal ? curr : acc
}, [])[0]
And then we filter our state
state.filter(element => element.id === max);
// or if `element.id` is of type number
// you need to cast `max` to Number first
const newMax = Number(max);
state.filter(element => element.id === newMax);
I'm not sure I didn't overcomplicate the logic but that's the way I came up with.