Copy array and remove strings? Javascript

I’m trying to make a copy of the array without all the strings with an “x” and attribute the new array without those “x” strings to the (deCode) variable below. Using for loop or push/pop or join/split methods. can anyone point me in the right direction? thank you

   var messageL = [ 'W', 'x', 'e', 'c', 'x', 'o', 'm', 'x', 'x', 'e', ''', 'x', 's', ' ', 'h', 'o', 'x', 'm', 'x', 'x', 'e'];
var deCode = [];

Answer

If you need to use a for loop, you can loop through the array and push each element to your new array.

var messageL = [ 'W', 'x', 'e', 'c', 'x', 'o', 'm', 'x', 'x', 'e', ''', 'x', 's', ' ', 'h', 'o', 'x', 'm', 'x', 'x', 'e'];
var deCode = [];
for (let i = 0; i < messageL.length; i ++) {
    if (messageL[i] !== "x") {
        deCode.push(messageL[i]);
    }
}

However, there’s a better way. Javascript has a filter method, which lets you get a new array with every single element in an old array that passes a test function.

var messageL = [ 'W', 'x', 'e', 'c', 'x', 'o', 'm', 'x', 'x', 'e', ''', 'x', 's', ' ', 'h', 'o', 'x', 'm', 'x', 'x', 'e'];


// The .filter function passes every element to the function that you provide. If the function returns true, then that element is copied into a new array. Otherwise, it is not. Note that it doesn't modify the old array
var deCode = messageL.filter(function (letter) {
    return letter !== "x"
});

You can actually shorten this even more by using an arrow function. This code does the exact same thing:

var messageL = [ 'W', 'x', 'e', 'c', 'x', 'o', 'm', 'x', 'x', 'e', ''', 'x', 's', ' ', 'h', 'o', 'x', 'm', 'x', 'x', 'e'];


var deCode = messageL.filter((element) => element !== "x");