0

take a look at this example:

let my_array = [1,2,4,5,6,7,8]



test = my_array.map(element=>{
    if(element!==1){
        return element
    }
})


console.log(test)

why map() function always return something if the statement does not match?

I know map function iterate over the indexes of array. but why returns null? we said return only if the statement is true.

how we can avoid null in return of map()?

update: I needed combination of map() and filter():

let my_array = [1, 2, 4, 5, 6, 7, 8]
test = my_array
  .filter(element => element !== 1)
  .map(element => element * 2);

console.log(test)
Babak Abadkheir
  • 2,222
  • 1
  • 19
  • 46

1 Answers1

6

.map will always create an array with the same number of items as in the original array. That's how it works. If you don't want to produce an array with the same number of elements, use .filter instead:

let my_array = [1, 2, 4, 5, 6, 7, 8]
test = my_array.filter(element => element !== 1);

console.log(test)

.map is only suited for transforming every element of an array into another value, eg:

let my_array = [1, 2, 4, 5, 6, 7, 8]
test = my_array.map(element => element * 2);

console.log(test)

If you need to both remove values and transform an element, then you can use both .filter and .map:

let my_array = [1, 2, 4, 5, 6, 7, 8]
test = my_array
  .filter(element => element !== 1)
  .map(element => element * 2);

console.log(test)
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320