I have a list like this :
var list = [apple, watermelon, pineapple]
And an array like this :
var array = {
fruit : [ [apple], [apple, watermelon], [pineapple, watermelon], [watermelon], [pineapple], [apple, pineapple] ]
count : [4, 7, 5, 3, 3, 2]
}
I want to create a new array with the occurence of each fruits and to obtain this :
result =
{
fruits : [apple, watermelon, pineapple]
count : [13, 15, 10]
I tried this :
var result = {
trigger : [apple, watermelon, pineapple],
count : []
}
for (i=0; i < array.fruits.length; i++){
var k = 0
for (j in result.trigger){
if (array.fruits[i].includes(j)) {
k += array.count[i]
}
result.count.push(k)
}
}
But I get 0 for all counts
Thanks in advance for helping
2
Answers
You can use
Array#reduce
and check in each iteration whether a fruit inarray.fuits[i]
is in yourlist
. If that is the case increase the according counter in your reducer accumulator.