andrasat
andrasat

Reputation: 13

Split is not doing anything when used inside filter

I tried using this function to filter an array based on index and return the splitted string into new array

const arr = ['arr 1','arr 2','arr 3','arr 4']
const newArr = arr.filter((val,index)=> {
  if(index <= 1) {
    return val.split(' ')
  }
})

newArr should return this,

[['arr','1'],['arr','2']]

But it return this,

["arr 1", "arr 2"]

Here is the code in JS BIN: https://jsbin.com/zoguwoyexe/edit?js,console

Split works inside map function, but I wonder why it doesn't work inside filter, anyone knows about this?

Upvotes: 1

Views: 192

Answers (1)

000
000

Reputation: 27247

filter expects you to return true-y or false-y values. It keeps trues and discards falses. It does not return the values you return, it returns a subset of the input array.

By using filter and map, like this, should get what you expect.

const arr = ['arr 1','arr 2','arr 3','arr 4']
const newArr = arr
  .filter((val,index) => (index <= 1))
  .map((val, index) => val.split(' '));

Upvotes: 2

Related Questions