0

I have the following code to add up all the sum of the numbers in the object:

const obj = {
  a: 1,
  b: 2,
  c: [1,2,3,4, [5,6,7]],
  d: {
    e: 1,
    f: 2,
  }
}


function sum(obj) {
  let res = 0;
  for(let key in obj) {
    const val = obj[key];
    if(typeof val === 'object' && !Array.isArray(val)) {
      res = res + sum(val);
    }
    if(Array.isArray(val)) {
      res = res + flattenArray(val);
    }
    else {
      //console.log(val)
      res = res + val;
    }
  }

  return res;
}

function flattenArray(arr) {
  let sum = 0;
  
  for(let i = 0; i<arr.length; i++) {
    const item = arr[i];

    if(!Array.isArray(item)) {
      sum = sum + item;
    } else {
      sum = sum + flattenArray(item);
    }
  }

  return sum; //34
}

sum(obj);

In this function, the sum returns 34[object Object]. So 34 is the correct answer, but I'm a little confused on why it has the string [object Object] here.

I went through my code and I see that at this line:

//console.log(val)

val is actually an object: { e: 1, f: 2 }. However, why was it not caught by this condition: if(typeof val === 'object' && !Array.isArray(val)) and go also into the else condition?

2
  • You have an if {} if {} else {} chain. Please focus on that. Commented Jan 21, 2021 at 23:19
  • You most likely intended to have an if {} else if {} else {} chain Commented Jan 21, 2021 at 23:22

1 Answer 1

1

You can flatten the array using a recursive function with Object.values(), and Array.flatMap), and sum the flattened array using Array.reduce():

const deepFlatten = obj =>
  Object.values(obj)
    .flatMap(o => typeof o === 'object' ? deepFlatten(o) : o)
    
const sum = arr => arr.reduce((s, n) => s + n, 0)

const obj = {"a":1,"b":2,"c":[1,2,3,4,[5,6,7]],"d":{"e":1,"f":2}}

const result = sum(deepFlatten(obj))

console.log(result)

The problem in the sum function is that you don't have an else between the 1st and 2nd/3rd cases, which means that object can be handled by the 1st if, and then by the 2nd if or it's attached else.

const obj = {
  a: 1,
  b: 2,
  c: [1, 2, 3, 4, [5, 6, 7]],
  d: {
    e: 1,
    f: 2,
  }
}

function sum(obj) {
  let res = 0;
  for (let key in obj) {
    const val = obj[key];
    if (typeof val === 'object' && !Array.isArray(val)) {
      res = res + sum(val);
       // the missing else
    } else if (Array.isArray(val)) {
      res = res + flattenArray(val);
    } else {
      res = res + val;
    }
  }

  return res;
}

function flattenArray(arr) {
  let sum = 0;

  for (let i = 0; i < arr.length; i++) {
    const item = arr[i];

    if (!Array.isArray(item)) {
      sum = sum + item;
    } else {
      sum = sum + flattenArray(item);
    }
  }

  return sum; //34
}

const result = sum(obj);

console.log(result);

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

7 Comments

Hi there! So here's what I don't understand, in my original code, what does the else case apply to? I thought else would be a catch-all case for anything that isn't part of the other 2 ifs. So I thought it meant to say, if it's not an object (first case), or it's not an array, then go into this else condition
When you have multiple if clauses, of which you want only one case to be applied, you need to chain them with else. When one of the ifs is true, it will be applied, and the chain will end. If you don't use else, every condition is checked, and applied if it's true. In your case the 2nd and 3rd clauses are chained with else, so if it the 2nd is false the 3rd would be applied. The 1st is not connected, and even if it's true, and the 2nd/3rd would be checked as well.
This is doc can help you.
Oh so else will only be applied to the if condition immediately preceding it, unless we use else if?
If you have multiple if clauses, and you want to stop as soon as one is true, you'll have to chain them with else if. The last else is the fallback - when no if is true. And yes, the else only refers to the if preceding it.
|

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.