Home > Software engineering >  How to add last field of arrays together
How to add last field of arrays together

Time:09-24

I'm trying to take this array, and add each of the last fields together ex: 22, 44, 88, 2, 6, 66, 11 and then put it into one variable using javascript. Also I would like to put the amount of products in the array into a different variable. Does anyone know a simple way to do this? Would I use a loop?

let products = [
    ["product1", "Small Widget", "159753", 33, 22],
    ["product2", "Medium Widget", "258456", 55, 44],
    ["product3", "Large Widget", "753951", 77, 88],
    ["product4", "Not a Widget", "852654", 11, 2],
    ["product5", "Could be a Widget", "654456", 99, 6],
    ["product6", "Ultimate Widget", "321456", 111, 66],
    ["product7", "Jumbo Small Medium Widget", "987456", 88, 11]
];

CodePudding user response:

Try this:

let products = [
    ["product1", "Small Widget", "159753", 33, 22],
    ["product2", "Medium Widget", "258456", 55, 44],
    ["product3", "Large Widget", "753951", 77, 88],
    ["product4", "Not a Widget", "852654", 11, 2],
    ["product5", "Could be a Widget", "654456", 99, 6],
    ["product6", "Ultimate Widget", "321456", 111, 66],
    ["product7", "Jumbo Small Medium Widget", "987456", 88, 11]
];


let sum = 0
products.forEach(product=>{
  sum  = product[product.length -1]
})

console.log(sum)


let product_of_elements = 1
products.forEach(product=>{
  product_of_elements *= product[product.length -1]
})

console.log(product_of_elements)

In the end, sum variable will contain the sum of all the last elements, and product_of_elements variable will contain their products.

CodePudding user response:

Yes, you need to loop. This will help you see how to access different parts of the arrays.

let products = [
    ["product1", "Small Widget", "159753", 33, 22],
    ["product2", "Medium Widget", "258456", 55, 44],
    ["product3", "Large Widget", "753951", 77, 88],
    ["product4", "Not a Widget", "852654", 11, 2],
    ["product5", "Could be a Widget", "654456", 99, 6],
    ["product6", "Ultimate Widget", "321456", 111, 66],
    ["product7", "Jumbo Small Medium Widget", "987456", 88, 11]
];

console.log(products.length);
console.log(products[0]);
console.log(products[0][3]);

  • Related