简体   繁体   中英

Extracting falsy values from array in Javascript

I am trying to write a function sortBool(arr) to take an array and return an object with the count for each kind of falsy value found.

For example:

sortBool([1, 0, 10, 2-2, Math.sqrt(-1)]); // should return {0: 2, NaN: 1}

Thus far:

const sortBool = arr => {
  index = 0; 
  let falsyTypes = {}; 
  while (index < arr.length) { 
    if(eval(arr[index])) {
      index++; 
    }else {
      //some code to determine what type of falsy value each element is and then add it to the object
    }
  }
  return falsyTypes; 

You could check the value and then count by taking the value as key.

 function sortBool(array) { return array.reduce((r, v) => { if (!v) { r[v] = (r[v] || 0) + 1; } return r; }, {}); } console.log(sortBool([1, 0, 10, 2 - 2, Math.sqrt(-1)])); 

The answer by @Nina Scholz is correct, and is a good way of solving the problem functionally. Learning JavaScript, on the long run, that is the way to go.

Just in case it requires too many new concepts at once, I'm providing a solution more in line with the function you implemented:

// you don't need lambda expressions, just a plain old function
function sortBool(arr) {
  var falsyTypes = {};

  // you can use a for for a slightly more compact syntax
  for(var index = 0; index < arr.length; index++) {
    var val = arr[index];

    // you don't need to eval. So please don't
    if (!val) {
      falsyTypes[val] = (falsyTypes[val] || 0) + 1;
    }
  }

  return falsyTypes; 
}

As you can see, the method is slightly longer than the one using reduce, but is functionally equivalent. Really, it is exactly the same.

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