skip to Main Content

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


  1. var list = ['apple', 'watermelon', 'pineapple']
    
    var array = {
      fruit: [
        ['apple'],
        ['apple', 'watermelon'],
        ['pineapple', 'watermelon'],
        ['watermelon'],
        ['pineapple'],
        ['apple', 'pineapple']
      ],
    
      count: [4, 7, 5, 3, 3, 2]
    }
    
    const values = Array(list.length).fill(0)
    
    // for each item of array.fruit
    for (let i = 0; i < array.fruit.length; i += 1) {
      // for each fruit in subarray
      for (const fr of array.fruit[i]) {
        // find index in list
        const index = list.indexOf(fr)
        // add count of fruits
        values[index] += array.count[i]
      }
    }
    
     
    
    console.log(values)
    Login or Signup to reply.
  2. You can use Array#reduce and check in each iteration whether a fruit in array.fuits[i] is in your list. If that is the case increase the according counter in your reducer accumulator.

    const list = ["apple", "watermelon", "pineapple"];
    const array = {
      fruit: [
        ["apple"],
        ["apple", "watermelon"],
        ["pineapple", "watermelon"],
        ["watermelon"],
        ["pineapple"],
        ["apple", "pineapple"]
      ],
      count: [4, 7, 5, 3, 3, 2]
    };
    
    const result = array.fruit.reduce((acc, curr, i) => {
      curr.forEach(fruit => (acc[list.indexOf(fruit)] += array.count[i]));
      return acc;
    }, Array(list.length).fill(0));
    
    console.log(result);
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search