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)
4
  • 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); Commented Jul 29, 2017 at 8:03
  • It's not possible. An efficient way to do this would be to use reduce developer.mozilla.org/en/docs/Web/JavaScript/Reference/… Commented Jul 29, 2017 at 8:05
  • I believe quantum computers are capable of solving this problem without iterating. Commented Jul 29, 2017 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: ocf.berkeley.edu/~shidi/cs61a/wiki/Iteration_vs._recursion). See example code at codepen.io/anon/pen/YxwdpR Commented Jul 30, 2017 at 23:29

2 Answers 2

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);

Sign up to request clarification or add additional context in comments.

Comments

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; }

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.