
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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" } ] } ] } ] } ]
Advertisements