Trying to do immutable way of pushing an array into existing array but somehow my code is not working.
function insertItem(array, action) {
return [
...array.slice(0, action.index),
action.item,
...array.slice(action.index)
]
}
const ori_arr = [{
id: 1,
name: 'james',
age: 10
}, {
id: 2,
name: 'terrance',
age: 20
}]
console.log(insertItem(ori_arr, {
action: {
index: 1,
item: {
id: 3,
name: 'she',
age: 44
}
}
}))
possibly wrong at the index part.
action.action.index- notaction.indexbecause that doesn't exist.{action: ... }in the function call is too much. You just want{index:1, item:...}constaffects it)