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

Remove element from nested array

I have this data:

const pages = [
  [
    {id: 1}, 
    {id:2}
  ],
  [
    {id: 3}, 
    {id:4}
  ],
];

What would the best and more efficient way to remove an element from this structure having 2 indexes as params?

e.g. index1 = 1 and index2 = 0 will remove pages[1][0] and pages will be:

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

const pages = [
  [
    {id: 1}, 
    {id:2}
  ],
  [
    {id:4}
  ],
];

>Solution :

You can use array.splice to remove an item from an array:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice

The splice() method changes the contents of an array by removing or
replacing existing elements and/or adding new elements in place. To
access part of an array without modifying it, see slice().

This is the demo with a function implementing what did you request for:

const pages = [
  [
    {id: 1}, 
    {id:2}
  ],
  [
    {id: 3}, 
    {id:4}
  ],
];

removeItem(1,0);
console.log(pages);

function removeItem(index1, index2){
  pages[index1].splice(index2, 1);
}
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