I'm trying to replace object(s) in an array from another array while keeping the index/order in place.
So arrayOne:
[
{
"color": "#f8edd1",
"selected": true
},
{
"color": "#d88a8a",
"selected": false
},
{
"color": "#474843",
"selected": false
},
{
"color": "#9d9d93",
"selected": true
},
{
"color": "#c5cfc6",
"selected": false
}
]
arrayTwo:
[
"#1c2130",
"#028f76",
"#b3e099",
"#ffeaad",
"#d14334"
]
my desired new array would be:
[
"#f8edd1",
"#028f76",
"#b3e099",
"#9d9d93",
"#d14334"
]
So the selected color(s), would still be in the same index/position in the array. The desired array can be a completely new array or updated arrayOne or Two. The main issue I ran into was mapping it when there was more than 1 object with the selected: true.
This was my first stab at it:
const selectedColors = arrayOne.filter(function (obj) {
return obj.selected === true
})
if (selectedColors) {
const lockedIndex = arrayOne.findIndex((obj) => {
if (obj.color === selectedColors[0].color) {
return true
}
})
const newColors = arrayTwo.splice(lockedIndex, 1, selectedColors[0].color)
console.log(newColors)
}
Also note that arrayOne is actually a React useState, but i'm not looking to update the useState, I'm doing something else with the newColors - but if it's easier to create a seperate useState to execute what i'm trying to do, that's fine.