'How do you extract an array or count the elements in Javascript if we don't know how big is it?
I have an array like this:
const fruits = ["apple", "peach"]
And I have a second array like this:
const sold = [
["sold", "not"],
["not", "sold"],
["sold", "not"]
];
function summarizeFruits(fruits,sold){
}
We don't know how big the first array is, but 2 elements are certain. The arrays in the second array have as many elements as there are fruits in the first.
We need to count which fruit was sold more and then print this on the console. How would you do this task in js if we didn't know the size of the first array?
I used array.length, but it wasn't a good option
Solution 1:[1]
I would approach with something like this:
First mapping the array with values instead of strings (1 for a sale, 0 otherwise)
Then creating a new array of object with each fruit and its number of sales
Finally printing the maximum of the array
const fruits = ['apple','pear']
const sold = [
["sold", "not"],
["not", "sold"],
["sold", "not"]
];
function summarizeFruits(fruits,sold){
const arr = sold.map(elem => elem.map(x => x === "sold" ? 1 : 0))
const totalSold = []
fruits.forEach((elem, index) => totalSold.push({fruit: elem, nbSold: arr.reduce((total,current) => total + current[index], 0)}))
//then printing the most sold fruit
const maximum = Math.max.apply(Math, totalSold.map(o => o.nbSold))
const mostSoldFruit = totalSold.find(x => x.nbSold === maximum)
console.log(`The most sold fruit is ${mostSoldFruit.fruit} with ${mostSoldFruit.nbSold}`)
}
summarizeFruits(fruits, sold)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | marc_s |