0

If my nested array named alpha has exactly same value as the object property in bravo, the object value should be added into the cost. After all the values in the fist nested array had finished went through the for-loop, the cost should be pushed into an array named charlie. However, I run console.log(charlie) and find that all values in charlie are 0, why this happens?

    var alpha = [["a", "b", "c"],["d", "e"]]
     
    var bravo = { a: 1, b: 2, c: 3, d: 4, e: 999 }

    var charlie = [];

        //For-loop 1
        for(let i = 0; i < alpha.length; i++){

            var cost = 0;

            const currentAlpha = alpha[i];

            //For-loop 2
            for(let j = 0; j < currentAlpha.length; j++){

                //For-loop 3
                for (let x in bravo) {
                    if (currentAlpha[j] == Object.getOwnPropertyNames(bravo[x])){
                        cost += bravo[x];
                    }
                  }
            }

          charlie.push(cost);

        }
        
        console.log(charlie);

0

2 Answers 2

1

You can use the built-in array function map to iterate the alpha array and then reduce to sum the bravo values for each element in those arrays:

const alpha = [
  ["a", "b", "c"],
  ["d", "e"]
]

const bravo = { a: 1, b: 2, c: 3, d: 4, e: 999 }

const charlie = alpha.map(arr => arr.reduce((acc, el) => {
  acc += (bravo[el] ?? 0)
  return acc
}, 0)
)

console.log(charlie)

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

Comments

1

Your If statement is never true.

You can do it like this.

 var alpha = [["a", "b", "c"],["d", "e"]]
         
        var bravo = { a: 1, b: 2, c: 3, d: 4, e: 999 }
    
        var charlie = [];
    
            //For-loop 1
            for(let i = 0; i < alpha.length; i++){
    
                var cost = 0;
    
                const currentAlpha = alpha[i];
    
                //For-loop 2
                for(let j = 0; j < currentAlpha.length; j++){
    
                    //For-loop 3
                    for (let x in bravo) {
                    
                        if (currentAlpha[j] == x ){
                            cost += bravo[x];
                        }
                      }
                }
    
              charlie.push(cost);
    
            }
            
            console.log(charlie);

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.