-1

Is there a way to remove all white spaces from an array in javascript. For eg: [' 1',' ','c ']; should be replaced with ['1','c'];. This https://stackoverflow.com/a/20668919/4877962 removes the element which is a white space, but how to remove the white space present in the element i.e ' 1' to '1'? I am a newbie to JS, please ignore if its a stupid question.

Mario
  • 4,784
  • 3
  • 34
  • 50
merilstack
  • 703
  • 9
  • 29
  • 1
    Iterate over the array and trim each string. Then you can use the solution you found to get rid of empty strings. Once you get more comfortable with JS, you can combine both operations in a reduce in order to accomplish it in a single iteration. – Lennholm Apr 18 '18 at 03:10

3 Answers3

2

If you just want to remove all white spaces from each string you could use

['  1',' ','c  '].map(item => item.trim())

If you want to remove all white spaces and empty strings you could try pigeontoe solution or this reduce implementation

const array = ['  1',' ','c  ']

const result = array.reduce((accumulator, currentValue) => {
    const item = currentValue.trim()

    if (item !== '') {
        accumulator.push(item);
    }

    return accumulator;
}, [])
Mario
  • 4,784
  • 3
  • 34
  • 50
0

Javascript has trim() function https://www.w3schools.com/jsref/jsref_trim_string.asp. Use can use map to loop through an array and trim() each element.

bird
  • 1,872
  • 1
  • 15
  • 32
0

You could use a combination of .map() and .trim() to iterate over the array and remove spaces. Then .filter() to filter out the empty strings like this:

const input = ['  1',' ','c  '];

const output = input
  .map(val => val.trim())
  .filter(val => val !== '')

console.log(output)
pigeontoe
  • 446
  • 3
  • 8