Home > OS >  JavaScript array all value show 0 when print using console.log
JavaScript array all value show 0 when print using console.log

Time:10-22

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

CodePudding user response:

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)

CodePudding user response:

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

  • Related