Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Adding an object to an array to a specific index in javascript

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!

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading