2

Is it possible to add up all duration values of an object array without iteration?

const data = [
  {
    duration: 10
    any: 'other fields'
  },
  {
    duration: 20
    any: 'other fields'
  }
]

Result should be '30'.

let result = 0
data.forEach(d => {
  result = result + d.duration
})
console.log(result)
user3142695
  • 15,844
  • 47
  • 176
  • 332
  • 3
    no, it is not possible to iterate an array without iteration - by the way, I recommend using reduce ... `let result = data.reduce((r, d) => r + d.duration, 0);` – Jaromanda X Jul 29 '17 at 08:03
  • It's not possible. An efficient way to do this would be to use reduce https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce – Fawaz Jul 29 '17 at 08:05
  • I believe quantum computers are capable of solving this problem without iterating. –  Jul 29 '17 at 11:34
  • While it is an unfeasible notion to attempt to iterate without using iteration, one may use recursion instead of iteration to extract the indicated object property value from each of the array's objects and total those values. In fact, "...iteration is just a special case of recursion (tail recursion)" (see: https://www.ocf.berkeley.edu/~shidi/cs61a/wiki/Iteration_vs._recursion). See example code at https://codepen.io/anon/pen/YxwdpR – slevy1 Jul 30 '17 at 23:29

2 Answers2

4

I does not work without some iteration, to get a sum of a specified property.

You could use Array#reduce with a callback and a start value of zero.

const data = [{ duration: 10, any: 'other fields' }, { duration: 20, any: 'other fields' }];
let result = data.reduce((r, d) => r + d.duration, 0);

console.log(result);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
3

You can't accomplish this without iteration. You can use array#reduce , which uses iteration.

const data = [
  {
    duration: 10,
    any: 'other fields'
  },
  {
    duration: 20,
    any: 'other fields'
  }
];

var result = data.reduce(
  (sum, obj) => sum + obj['duration'] 
  ,0
);

console.log(result)
.as-console-wrapper { max-height: 100% !important; top: 0; }
Hassan Imam
  • 21,956
  • 5
  • 41
  • 51