Removing an item when using Array.prototype.map() in Javascript

180
April 02, 2018, at 02:15 AM

I currently have a variable that contains an array of numbers

let numbersArray = [12, 15, 19, 20];

When looping over it I want to delete the entry if it is a certain value

let numbersArray = [12,15,19,20],
    filteredNumbersArray = numbersArray.map(function(value)
    {
        if(value === 15)
        {
            //delete the value
        } else {
            return value * 2;
        }
    });

In regards to using .filter(), the value must be mutatable, I have updated the example

I have searched through MDN but couldn't find anything about removing an element within a map().

The Rubber Duck didn't help either

Answer 1

You could filter and then map

var array = [12, 15, 19, 20], 
    result = array 
        .filter(v => v !== 15) 
        .map(v => 2 * v); 
         
console.log(result);

Or use the swiss knife of all array manipulations: Array#reduce

var array = [12, 15, 19, 20], 
    result = array.reduce((r, v) => v !== 15 ? r.concat(v): r, []); 
         
console.log(result);

With some optimizations

var array = [12, 15, 19, 20], 
    result = array.reduce(function (r, v) { 
        if (v !== 15) { 
            r.push(2 * v); 
        } 
        return r; 
    }, []); 
         
console.log(result);

Answer 2

map can't remove values. If you need to simultaneously map and filter, your options are:

  1. filter, then map, e.g.:

    filteredNumbersArray = numbersArray.filter(function(v) { return v !== 15; })
                                       .map(function(v) { return v * 2; });
    

    or with ES2015+ syntax:

    filteredNumbersArray = numbersArray.filter(v => v !== 15)
                                       .map(v => v * 2);
    

    or

  2. Write your own thing, probably:

    filteredNumbersArray = [];
    numbersArray.forEach(function(v) {
        if (v !== 15) {
            filteredNumbersArray.push(v * 2);
        }
    });
    

    or with ES2015+ syntax:

    filteredNumbersArray = [];
    for (const v of numbersArray) {
        if (v !== 15) {
            filteredNumbersArray.push(v * 2);
        }
    }
    

    (You can also [ab]use reduce here, but it doesn't gain you anything worth having, and costs clarity.)

    If it comes up a lot for you, give yourself a combined map-and-filter function that uses some special return value to indicate that the entry should be dropped.

Answer 3

Map doesn't remove values it just mutates them. You could set the value to null but that is probably not your intent.

Filter might server you better
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter

let numbersArray = [12,15,19,20],
filteredNumbersArray = numbersArray.filter(function(value)
{
    return value != 15
});

This would return an array without the number 15.

Answer 4

You wanna do something like:

const newNumberArray = numbersArray.filter(myNumber =>myNumber !== 15).map(n => n*2)

READ ALSO
Typescript can class methods allow method chaining without returning 'this'?

Typescript can class methods allow method chaining without returning 'this'?

I have made a Mycalculator class that implements the following Calculator Interface to be method chaining

144
Javascript Image Recognition Game

Javascript Image Recognition Game

So I'm working on a school projectThe user is presented an image recognition game with one main image (geometric shape) and under a line of other images (geometric shapes)

241
How to get detailed data from API?

How to get detailed data from API?

I have a task to doI have to get data from Pokemon API, and show them on website

214
Event Listener not working in external javascript file

Event Listener not working in external javascript file

I'm having trouble getting this click event listener at the bottom to work from my external fileIt works when I call in the HTML, but not in the file

169