izaakxaos
izaakxaos

Reputation: 57

map function returns item even if condition is not true

Here's my code:

//input = aaaaaaa,                ddd,            ,    
 asdsad,

newUser =
users
  .split(',')
  .map(item => {
    item = item.trim();
    if(item.length > 0) {
      return item;
    }
}).join();

//output = aaaaaaa,ddd,,asdsad,

So my question is why if item has 0 length is returned from map function? Am I missing something obvious?

//EDIT:

Yeah, now its removoing empty strings but what about white spaces? My result still looks like this:

asdasdasd , aa

I want to have:

asdasdasd,aa

Upvotes: 0

Views: 530

Answers (3)

Maheer Ali
Maheer Ali

Reputation: 36594

The length of the array returned by map() will always be equal to the length of orignal array. When you want to remove elements of array accoring to condition use filter() .

In the particular case you can remove white spaces first from the string and then remove two or more adjacent commas with single comma.

let input = 'aaaaaaa,                ddd,            ,     asdsad,'
let res = input.replace(/\s+/g,'').replace(/,{2,}/,',');
console.log(res)

Upvotes: 0

brk
brk

Reputation: 50346

You can use String replace and regex to remove all white space

let input = 'aaaaaaa,                ddd,            ,    asdsad,';
let newData = input.replace(/ /g, '');;
console.log(newData)

Alternatively you can use reduce function. Inside reduce callback check the the length of the string and if condition satisfies then push it with the accumulator. Finally use join to cancat using , delimiter

let users = " aaaaaaa,                ddd,            ,   asdsad"
let newUser = users.split(',')
  .reduce(function(acc, curr) {
    if (curr.trim().length > 0) {
      acc .push(curr.trim());
    }
    return acc;
  },[]).join(',')
console.log(newUser)

Upvotes: 0

yajiv
yajiv

Reputation: 2941

As per doc of .map()

The map() method creates a new array with the results of calling a provided function on every element in the calling array.

So using map you can perform some opration on each element, you can not omit any element.

If you want to omit some element based on some condtion then use .filter().

For your case you can first use map() for triming all element then use filter() to removed element whose length is not >0.

var input = "aaaaaaa,                ddd,            ,asdsad   ";

var output = input.split(',').map(item => {
    item = item.trim();
    return item;
}).filter(item => {
    return item.length > 0;
}).join();

console.log(output);

Upvotes: 1

Related Questions