'How to evaluate an array element and assign the result to an object key in JavaScript

Write a function that takes one parameter, an array of numbers. The function should return an object with three keys, lessThanTen, equalToTen, and greaterThanTen. The values should represent the number of elements from the array that are less than, equal to, or greater than ten respectively.

Here is my latest attempt:

function objTen(arr) {
  // YOUR CODE HERE
  for (let i = 0; i < arr.length; i++) {
    if (arr[i] < 10) {
      let lessThanTen = arr[i];
      return {lessThanTen: lessThanTen};
    } if (arr[i] === 10){
      let equalToTen = arr[i];
      return {equalToTen: equalToTen};
    } else {
      let greaterThanTen = arr[i];
      return {greaterThanTen: greaterThanTen};
    }
  }
}


module.exports = objTen;

Error message received: objTen 1) Returns the object with respective values (1). 2) Returns the object with respective values (2). 3) Returns the object with respective values (3).

0 passing (7ms) 3 failing

  1. objTen Returns the object with respective values (1).:

    AssertionError: expected { lessThanTen: 1 } to deeply equal { Object (lessThanTen, equalToTen, ...) }

    • expected - actual

    {

    • "lessThanTen": 1
    • "equalToTen": 3
    • "greaterThanTen": 1
    • "lessThanTen": 2 }

    at Context. (.guides/secure/test8.8.1.js:6:51) at processImmediate (internal/timers.js:439:21)

  2. objTen Returns the object with respective values (2).:

    AssertionError: expected { greaterThanTen: 23 } to deeply equal { Object (lessThanTen, equalToTen, ...) }

    • expected - actual

    {

    • "greaterThanTen": 23
    • "equalToTen": 2
    • "greaterThanTen": 3
    • "lessThanTen": 2 }

    at Context. (.guides/secure/test8.8.1.js:13:55) at processImmediate (internal/timers.js:439:21)

  3. objTen Returns the object with respective values (3).:

    AssertionError: expected { greaterThanTen: 67 } to deeply equal { Object (lessThanTen, equalToTen, ...) }

    • expected - actual

    {

    • "greaterThanTen": 67
    • "equalToTen": 2
    • "greaterThanTen": 2
    • "lessThanTen": 3 }

    at Context. (.guides/secure/test8.8.1.js:20:55) at processImmediate (internal/timers.js:439:21)

I have tried using nested loops but that did not work. I have tried putting the variables after the for loop line and before the if statements but that did not work either.

I teach a high school Intro to JavaScript class and this is one of the assignments. The course has no solution guide for the teacher so I have to complete all the graded assignments so I can grade the students' work and help them troubleshoot their own efforts. Some of the solutions below are too advanced for the students at this time and the class is in Codio so it has preprogrammed solution expectations and some of the solutions don't meet them so I get errors when I try to use them. Since realizing I was reading the last sentence of the prompt wrong, I have tried using the reduce method but I am not understanding how to plug it into my existing code.

Here is my current effort:

function objTen(arr) {
  // YOUR CODE HERE
  let lessThanTen  ;
  let equalToTen ; 
  let greaterThanTen  ;
  let val = 10;
  
  
  for (let i = 0; i < arr.length; i++) {
    let number = arr[i];
    if (number < 10) {
      lessThanTen = (number, val) => arr.reduce((a, v) => (v < val ? a + 
      1 : a), 0);
    } if (number === 10){
      equalToTen = (number, val) => arr.reduce((a, v) => (v === val ? a 
      + 1 : a), 0);
    } else {
      greaterThanTen = (number, val) => arr.reduce((a, v) => (v > val ? 
      a + 1 : a), 0);
    }
  }
  return {
    lessThanTen: lessThanTen,
    equalToTen: equalToTen,
    greaterThanTen: greaterThanTen,
  };

}
module.exports = objTen;

Here is the error message CodobjTen 1) Returns the object with respective values (1). 2) Returns the object with respective values (2). 3) Returns the object with respective values (3).

0 passing (7ms) 3 failing

  1. objTen Returns the object with respective values (1).:

    AssertionError: expected { Object (lessThanTen, equalToTen, ...) } to deeply equal { Object (lessThanTen, equalToTen, ...) }

    • expected - actual

    {

    • "equalToTen": [Function]
    • "greaterThanTen": [Function]
    • "lessThanTen": [Function]
    • "equalToTen": 3
    • "greaterThanTen": 1
    • "lessThanTen": 2 }

    at Context. (.guides/secure/test8.8.1.js:6:51) at processImmediate (internal/timers.js:439:21)

  2. objTen Returns the object with respective values (2).:

    AssertionError: expected { Object (lessThanTen, equalToTen, ...) } to deeply equal { Object (lessThanTen, equalToTen, ...) }

    • expected - actual

    {

    • "equalToTen": [Function]
    • "greaterThanTen": [Function]
    • "lessThanTen": [Function]
    • "equalToTen": 2
    • "greaterThanTen": 3
    • "lessThanTen": 2 }

    at Context. (.guides/secure/test8.8.1.js:13:55) at processImmediate (internal/timers.js:439:21)

  3. objTen Returns the object with respective values (3).:

    AssertionError: expected { Object (lessThanTen, equalToTen, ...) } to deeply equal { Object (lessThanTen, equalToTen, ...) }

    • expected - actual

    {

    • "equalToTen": [Function]
    • "greaterThanTen": [Function]
    • "lessThanTen": [Function]
    • "equalToTen": 2
    • "greaterThanTen": 2
    • "lessThanTen": 3 }

    at Context. (.guides/se

cure/test8.8.1.js:20:55) at processImmediate (internal/timers.js:439:21)io gives for the code above:



Solution 1:[1]

Some things are wrong with your code:

  1. When you do return {lessTanTen: someNumber}, you return from the function, so your function will not return an object with the 3 different keys, but it will return at the first iteration of you for loop.

  2. The variable you assign to lessThanTen is not the number of element that are less than 10, but the element itself, when you do let lessThanTen = elements[i]

You have 2 solutions:

First, if you want to keep using a loop:

function objTen(arr) {
  let lessThanTen = 0, equalToTen = 0, greaterThanTen = 0;
  for (let i = 0; i < arr.length; i++) {
    if (arr[i] < 10) {
      lessThanTen += 1;
    } if (arr[i] === 10){
      equalToTen += 1
    } else {
      greaterThanTen += 1;
    }
  }
  return {
    lessThanTen: lessThanTen,
    equalToTen: equalToTen,
    greaterThanTen: greaterThanTen
  }
}

There is also a second way of doing this using reduce():

function objTen(arr) {
  return arr.reduce((accumulator, current)=> {
    if (current < 10) {
    return ({
      ...accumulator,
      lessThanTen: accumulator.lessThanTen + 1
    })
    } else if (current == 10) {
      return ({
        ...accumulator,
        equalToTen: accumulator.equalToTen + 1
      })
    } else {
      return ({
        ...accumulator,
        greaterThanTen: accumulator.greaterThanTen + 1
      })
    }
  }, {lessThanTen: 0, equalToTen: 0,  greaterThanTen: 0})
}

The second solution is more advanced and usually preferred but both have the same output.

Solution 2:[2]

This will event work with another number, but will be 10 by default:

const getObject = (arr = [], num = 10) => {
  return arr.reduce((acc, curr) => {
    if (curr < num) acc.less += 1;
    if (curr === num) acc.equal += 1;
    if (curr > num) acc.greater += 1;
    return acc;
  }, { less: 0, equal: 0, greater: 0 })
}

console.log(getObject([8,9,10,12,13,14]))

// { less: 2, equal: 1, greater: 3 }

Solution 3:[3]

One possible solution/implementation:

const objTen = (arr = [10, 10, 8, 8, 12, 13, 7, 4, 10, 33]) => (
    arr.reduce((f, i) => ({...f, ...(
    typeof i === 'number'
    ? i < 10
      ? { lessThanTen : (f.lessThanTen || 0) + 1}
      : i === 10
        ? { equalToTen: (f.equalToTen || 0) + 1}
        : { greaterThanTen : (f.greaterThanTen || 0) + 1}
    : { notAnumber : (f.notAnumber || 0) + 1}
  )}) , {})
);

Explanation

  1. Use reduce to iterate over each element in the input-array
  2. As a simple precaution, ensure the input is number (& if it's not, simply account for it as notAnumber
  3. Check if an element is less than 10, equal to 10 or greater than 10.
  4. Accordingly update the relevant counter

If the reader is interested, they may choose to learn about ... (spread operator), ? : (ternary operator). The: (f.lessThanTen || 0), will either get the number of elements previously counted as lessThanTen or (||) zero. The || will ensure that if lessThanTen is null or undefined, then 0 will be picked. Thus, the first time a lessThanTen element is processed, it will be counted as 0 + 1 (ie 1). And, when a lessThanTen array-element is processed a second time, it will be counted as 1 + 1 (ie, 2). If it helps, we may explore using ?? operator as well.

Code-snippet

const objTen = (arr = [10, 10, 8, 8, 12, 13, 7, 4, 10, 33]) => (
  arr.reduce((f, i) => ({ ...f,
    ...(
      typeof i === 'number' ?
      i < 10 ?
      {
        lessThanTen: (f.lessThanTen || 0) + 1
      } :
      i === 10 ?
      {
        equalToTen: (f.equalToTen || 0) + 1
      } :
      {
        greaterThanTen: (f.greaterThanTen || 0) + 1
      } :
      {
        notAnumber: (f.notAnumber || 0) + 1
      }
    )
  }), {})
);


console.log('default-array: [10, 10, 8, 8, 12, 13, 7, 4, 10, 33]\n', objTen());
console.log('array: [0, -1, 10, 11]\n', objTen([0, -1, 10, 11]));
console.log("['asdf', 10, 9]\n", objTen(['asdf', 10, 9]));

Solution 4:[4]

Solved!!

function objTen(arr) {
  // YOUR CODE HERE
  let lessThanTen = [] ;
  let equalToTen = []; 
  let greaterThanTen = [];

  for (let i = 0; i < arr.length; i++){
    let number = arr[i];
    if (number < 10) {
      lessThanTen.push(number);
    } else if (number === 10) {
        equalToTen.push(number);
      } else {
        greaterThanTen.push(number);
      }
    }
  
  // console.log("less than ten:" lessThanTen);
  // console.log("equal to ten:" equalToTen);
  // console.log("greater than ten:" greaterThanTen);

  return {
    lessThanTen: lessThanTen.length,
    equalToTen: equalToTen.length,
    greaterThanTen: greaterThanTen.length,
  };

}
module.exports = objTen;

Thanks for all the suggestions.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 maxpsz
Solution 3
Solution 4 Shannon Rachal