-2

i am trying to return the sum of the first 4 grid values from the object below (expected output 5)

[
  {
    "id": 1,
    "grid": 1
  },
  {
    "id": 2,
    "grid": 2
  },
  {
    "id": 3,
    "grid": 1
  },
  {
    "id": 4,
    "grid": 1
  },
  {
    "id": 5,
    "grid": 1
  }
]



data.map(item => {
   console.log(item.grid);
});

Relatively new with .map, I would usually use a forwhile iterator but wondered if someone could suggest a more es6 style pattern for solving the problem.

James
  • 281
  • 3
  • 9
  • you can combine .slice and .reduce `data.slice(0,4).reduce((acc, currV) => acc + currV.grid, 0)` check more on [How to find the sum of an array of numbers](https://stackoverflow.com/questions/1230233/how-to-find-the-sum-of-an-array-of-numbers) – elreeda Jan 13 '20 at 16:36
  • If you want to sum, probably [.reduce](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce) is a better option than `.map` – Calvin Nunes Jan 13 '20 at 16:36

2 Answers2

2

You can use .slice() to cut the Array down to the Elements you want, and then .reduce() to sum up; getting the grid value with Destructuring

const data = [
  {"id": 1, "grid": 1},
  {"id": 2, "grid": 2},
  {"id": 3, "grid": 1},
  {"id": 4, "grid": 1},
  {"id": 5, "grid": 1}
];

const result = data.slice(0, 4).reduce((a, {grid}, i) => {
  return a += Number(grid);
}, 0);

console.log(result)
Shiny
  • 4,945
  • 3
  • 17
  • 33
1

use slice to get first 4 objects from array and then use reduce to sum the grid.

const input = [{
    "id": 1,
    "grid": 1
  },
  {
    "id": 2,
    "grid": 2
  },
  {
    "id": 3,
    "grid": 1
  },
  {
    "id": 4,
    "grid": 1
  },
  {
    "id": 5,
    "grid": 1
  }
];

console.log(input.slice(0, 4).reduce((a, {
  grid
}) => a + grid, 0));
Barmar
  • 741,623
  • 53
  • 500
  • 612
random
  • 7,756
  • 3
  • 19
  • 25