Remove item from a nested array by indices in JavaScript


Suppose, we have a nested array of objects like this −

const arr = [
   { value: 'some value' },
   {
      array: [
         { value: 'some value' },
         {
            array: [
               { value: 'some value' },
               { value: 'some value' },
            ],
         },
         { value: 'some value' },
         {
            array: [
               { value: 'some value' },
               {
                  array: [
                     { value: 'delete me' },
                     { value: 'some value' },
                  ]
               },
            ],
         },
      ],
   }
];

We are required to write a JavaScript function that takes in one such array as the first argument and an array of indices as the second argument.

Our function should delete the value property at all the indices specified by the array (second argument).

Example

The code for this will be −

const arr = [
   { value: 'some value' },
   {
      array: [
         { value: 'some value' },
         {
            array: [
               { value: 'some value' },
               { value: 'some value' },
            ],
         },
         { value: 'some value' },
         {
            array: [
               { value: 'some value' },
               {
                  array: [
                     { value: 'delete me' },
                     { value: 'some value' },
                  ]
               },
            ],
         },
      ],
   }
];
const keys = [1, 3, 1, 0];
const getKeys = (arr, keys) => {
   const recursiveFind = (arr, level) => {
      const res = [];
      arr.forEach((el, ind) => {
         if (keys[level] !== ind) {
            return res.push(el);
         };
         if (level + 1 !== keys.length && el.array) {
            res.push({ array: recursiveFind(el.array, level + 1) });
         };
      });
      return res;
   };
   return recursiveFind(arr, 0);
};
console.log(JSON.stringify(getKeys(arr, keys), undefined, 4));

Output

And the output in the console will be −

[
   {
      "value": "some value"
   },
   {
      "array": [
         {
            "value": "some value"
         },
         {
            "array": [
               {
                  "value": "some value"
               },
               {
                  "value": "some value"
               }
            ]
         },
         {
            "value": "some value"
         },
         {
            "array": [
               {
                  "value": "some value"
               },
               {
                  "array": [
                     {
                        "value": "some value"
                     }
                  ]
               }
            ]
         }
      ]
   }
]

Updated on: 23-Nov-2020

982 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements