0

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; 
2
  • Welcome to Stack Overflow! If you post some code showing what you've tried so far and what's going wrong with it, we'll be better able to help you. Commented Feb 18, 2019 at 21:51
  • I am trying to write a function Where? What have you tried? Commented Feb 18, 2019 at 21:56

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.