-1

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!

  • 1
    [Array.prototype.splice](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice) – KooiInc Jun 27 '22 at 13:14
  • I think this [question](https://stackoverflow.com/questions/586182/how-to-insert-an-item-into-an-array-at-a-specific-index-javascript) is for you. – Dvalin99 Jun 27 '22 at 13:16

1 Answers1

0

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);
DanteDX
  • 1,059
  • 7
  • 12