简体   繁体   中英

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

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); 

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) 

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) 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM