Raziel
Raziel

Reputation: 1566

multi splice (or similar) to remove a number of objects in array

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?

Upvotes: 1

Views: 40

Answers (4)

Langlois.dev
Langlois.dev

Reputation: 2141

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.

Upvotes: 0

Shakya Peiris
Shakya Peiris

Reputation: 612

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)

Upvotes: 0

Unmitigated
Unmitigated

Reputation: 89384

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);

Upvotes: 0

tenshi
tenshi

Reputation: 26342

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)));

Upvotes: 2

Related Questions