Home > Back-end >  multi splice (or similar) to remove a number of objects in array
multi splice (or similar) to remove a number of objects in array

Time:01-13

So i currently have 2 arrays:

const getUniqueRowErrors = [1,3]

const data = [
 {identifier: '000'},
 {identifier: '111'},
 {identifier: '222'},
 {identifier: '3333'},
 {identifier: '444'}
]

The idea is i want to remove the the elements based off the getUniqueRowErrors, so I want the 1st,and 3rd element removed from the the data array, so the end result being:

const data = [
 {identifier: '111'},
 {identifier: '3333'},
 {identifier: '444'}
]

I tried the following but the desired result is incorrect:

const filteredData = getUniqueRowErrors.map((rowToRemove) => data.splice(rowToRemove));

Any ideas how to do the above?

CodePudding user response:

Simply filter by index and check if the index is in the row errors array:

const getUniqueRowErrors = [1,3]

const data = [
 {identifier: '000'},
 {identifier: '111'},
 {identifier: '222'},
 {identifier: '3333'},
 {identifier: '444'}
];

console.log(data.filter((_, i) => !getUniqueRowErrors.includes(i   1)));

CodePudding user response:

Use Array#filter.

const getUniqueRowErrors = new Set([1,3]);
const data = [
 {identifier: '000'},
 {identifier: '111'},
 {identifier: '222'},
 {identifier: '3333'},
 {identifier: '444'}
]
let res = data.filter((_, i) => !getUniqueRowErrors.has(i   1));
console.log(res);

CodePudding user response:

You need to provide a length to the splice method as the second parameter. In your case, you have to set it to 1. Also since you are not removing items based on the zero-indexed method, you have to subtract 1 from rowToRemove.

data.splice(rowToRemove - 1, 1)

CodePudding user response:

const getUniqueRowErrors = [1,3];

const data = [
 {identifier: '000'},
 {identifier: '111'},
 {identifier: '222'},
 {identifier: '3333'},
 {identifier: '444'}
];

const filteredData = data.filter((row, i) => !getUniqueRowErrors.includes(i   1));

This returns a new array with the rows removed. Documentation on the filter function can be found here. The .filter removes any elements that don't pass the test provided. The .includes looks for the current index within the getUniqueRowErrors array and if found removes it due to the ! at the start.

  • Related