JavaScript create array with .map() with empty items (sparse array)

Viewed 137

Say I have an array

[1,2,1,2,1];

I want to use .map() to return a new array which is the same as the old one but the item is missing in the new array if it was 2 in the old one. So the new array would be:

const newArray = [1, ,1, ,1];

So the code would look something like:

const newArray = [1,2,1,2,1].map(d => d === 1 ? d : "not sure how to return empty item here");

But I don't know what to return to make the array have a missing element.

edit: I suggested using .map() because I didn't realise it is not possible to go from an array to sparse array (as helpfully explained in their comment below). In this case a solution not using .map() is OK.

3 Answers

You need to return undefined:

const newArray = [1,2,1,2,1].map(d => d === 1 ? d : undefined);
console.log(newArray);

This is an example on how empty elements are treated in JavaScript:

arr = [1,2,3];
newArr = arr.concat([, , , 5,6]);
console.log(newArr);

You could just return null:

const newArray = [1,2,1,2,1].map(d => d === 1 ? d : null);
const array = [1,2,1,2,1];
const newArray = Array(array.length);

array.map((item, index) => item !==2 ? newArray[index] = item : null);

// newArray -> [ 1, <1 empty slot>, 1, <1 empty slot>, 1 ]
Related