Select objects within an array - Javascript

1

to see if you can help me, I just start with JS ... I need to access within the array and the "cost" objects to make the total average cost.

var foods = [
    { id: 00, name: 'sausage', from: 'Spain', cost: 160, gluten: false },
    { id: 01, name: 'pepperoni', from: 'Italy', cost: 500, gluten: false },
    { id: 02, name: 'cheese', from: 'Holland', cost: 110, gluten: true },
]

This is the code that I made, but only the first cost (160) is added to me, there is no way to go adding up and then do the average cost:

  var suma = 0;

function foodsCost (){
    for (var i = 0; i<foods.length; i++){
        var costs = suma += foods[i].cost;      
        return costs;
    }
}

function averageCost () {
    var operator = foodsCost() / 3;
    return operator;
}

averageCost()

Thanks in advance!

    
asked by Miss_Sibavi 18.10.2018 в 11:32
source

3 answers

4

There are several ways to do what you want:

  • With a loop
  • Navigating the array with the forEach (similar to the loop)
  • adding everything with the reduce method

const foods = [
  { id: 00, name: 'sausage', from: 'Spain', cost: 160, gluten: false },
  { id: 01, name: 'pepperoni', from: 'Italy', cost: 500, gluten: false },
  { id: 02, name: 'cheese', from: 'Holland', cost: 110, gluten: true },
];

//bucle
let suma=0;
for (let i = 0; i < foods.length; i++) {
  suma += foods[i].cost;
}

console.log(suma);

//forEach

suma = 0;
foods.forEach(elem => suma += elem.cost);

console.log(suma);

//reduce: el 0 es el valor inicial del acumulador
suma = foods.reduce((acumulador,elem) => acumulador + elem.cost, 0);

console.log(suma)

//en todos los casos, la media se calcula sencillamente dividiendo la suma
const media= suma / foods.length;

console.log(media);
    
answered by 18.10.2018 / 11:54
source
2

You can add the values within a forEach simply by this: suma += item.cost;

In addition, you should use the total number of items in the array for the average, not the value 3 arbitrarily, since it will give a wrong value when the array does not have exactly three elements.

The code would be like this (the name of some functions has been changed, giving it more descriptive names):

var foods = [{
    id: 00,
    name: 'sausage',
    from: 'Spain',
    cost: 160,
    gluten: false
  },
  {
    id: 01,
    name: 'pepperoni',
    from: 'Italy',
    cost: 500,
    gluten: false
  },
  {
    id: 02,
    name: 'cheese',
    from: 'Holland',
    cost: 110,
    gluten: true
  },
]


function sumCost() {
  var suma = 0;
  foods.forEach(item => {
    suma += item.cost;
  });
  return suma;
}

function averageCost() {
  var operator = sumCost() / foods.length;
  return operator;
}

var avgCost = averageCost();
console.log(avgCost);
    
answered by 18.10.2018 в 11:54
1

I suggest a possible solution to your problem in a few lines:

var foods = [
{ id: 00, name: 'sausage', from: 'Spain', cost: 160, gluten: false },
{ id: 01, name: 'pepperoni', from: 'Italy', cost: 500, gluten: false },
{ id: 02, name: 'cheese', from: 'Holland', cost: 110, gluten: true },
]

let avgCost=0;
foods.forEach(function(element) {
  avgCost += element.cost ;
});
avgCost = avgCost/foods.length;
    
answered by 18.10.2018 в 11:47