I have an array like the following
const inputArray = [
{
_id: "D01",
name: "Sky",
},
{
_id: "D02",
name: "Space",
},
{
_id: "D03",
name: "Black",
},
{
_id: "D04",
name: "Yello",
},
];
How to write a function so that I can insert another object say,
const dataToBeInserver = {
_id: "A01",
name: "Watch",
};
to a specified index, lets say at index 2.
Thanks!
>Solution :
simply slice the parts and insert the desired array in the middle, just follow the code for reference. Thanks!
const inputArray = [
{
_id: "D01",
name: "Sky",
},
{
_id: "D02",
name: "Space",
},
{
_id: "D03",
name: "Black",
},
{
_id: "D04",
name: "Yello",
},
];
const dataToBeInserver = {
_id: "A01",
name: "Watch",
};
const indexWhereToInsert = 2;
const finalObject = [
...inputArray.slice(0, indexWhereToInsert),
dataToBeInserver,
...inputArray.slice(indexWhereToInsert),
];
console.log(finalObject);