Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Push to an Array using a for loop

Tags:

javascript

im a JS newbie. Trying to figure out this problem below. I am stuck on the "if" statement and not sure exactly what to put in. Also im not sure if my "push" is setup right

// Define a function named `compact` that accepts an array and returns
// another array with all the falsey values removed from it. For example,
// if this array was passed in:
//   [1, 4, 0, '', undefined, false, true, null, {mj: 'mj'}, 'Hello']
// the function would return this, as a result:
//   [1, 4, true, {mj: 'mj'}, 'Hello']

var compact = function (array) {
    var truthyValues = [];
    for (var i = 0; i < array.length; i += 1) {
        if () {
            truthyValues.push[i];
        }
    }
    return truthyValues;
};
like image 290
jstone Avatar asked Dec 26 '22 16:12

jstone


2 Answers

You're close. Here's what the if should be:

if (array[i]) {
    truthyValues.push(array[i]);
}

Since you want to check for truthiness of each array element, just put array[i] in the if block. That gets the value of the array at i, and will evaluate as true if that value is truthy.

Then push not i - the index into array - but array[i], so that the actual value is in truthyValues.

like image 121
Scott Mermelstein Avatar answered Dec 28 '22 06:12

Scott Mermelstein


Just put the value you want to check is truthy in the if statement, since the if statement checks for truthiness.

if(array[i]){
  truthyValues.push(array[i]);
}
like image 42
scrblnrd3 Avatar answered Dec 28 '22 05:12

scrblnrd3