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]
];
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.
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]
];
// how many items in products? (how many times to loop.)
console.log(products.length);
// get the first item (array).
console.log(products[0]);
// get the 4th item ([3]) in the 1st array ([0]).
console.log(products[0][3]);
One simple solution
const 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;
const productItems = [];
products.forEach((product) => {
const len = product.length;
sum += product[len - 1]; // Add last number
productItems.push(product[1]); // Add product name to an array
})
console.log(sum);
console.log(productItems);