DEV Community

Discussion on: JavaScript Array Reduce Doesn't Like Objects

Collapse
 
sabbin profile image
Sabin Pandelovitch

"JavaScript reduce doesn't like objects".... Of course it doesn't, it's an array prototype method.... Second you are iterating through an array of objects. Third since when second guessing is a method of programming.... Was this post a like a journal entry? Cause it would make more sense

Collapse
 
rfornal profile image
bob.ts

It is more like a journal entry. Something to remind me not to do that again.

Collapse
 
jimmymcbride profile image
Jimmy McBride

First) JavaScript loves objects. It makes sense that a reduce function would be able to handle objects since that's what everything is in JavaScript anyways. Why cut out your first-class citizens?

Second) Yup. Arrays are objects too. What's the problem with iterating through a list of objects? Often times you will get back an array of objects from a back end API anyways. It would be pretty annoying if you could not reduce an array of objects by a key in the object type you were iterating over.

Thirdly) Second-guessing is a beautiful method when it comes to programming. Doubt is a very important quality of a scientific, empirical thinker.

Collapse
 
sabbin profile image
Sabin Pandelovitch • Edited

I didn't stated that Javascript doesn't like objects... I quoted the title of the article as it's wrong, it's just like saying "Javascript string split doesn't like arrays"

Array are objects too, yes indeed.

Assume the following example

const array = [1, 2, 3];
const object = { a: 1, b: 2, c: 3 };

console.log(array.constructor); //array
console.log(object.constructor); //object

array.reduce((acc, val) => acc + val, 0); //6
object.reduce((acc, val) => acc + val, 0); //error

array.a = 4;

console.log(array.constructor); //still array
array.reduce((acc, val) => acc + val, 0); //still 6
console.log(Object.keys(array)); // ["0", "1", "2", "a"]

So yes, arrays are objects so therefore they can access object prototype methods, but not all objects are arrays so they cannot access the array prototype methods...

"What's the problem with iterating through a list of objects?"

There is no problem with this, I was trying to state that the title is misleading again. The object is not reduced, the list objects is reduced and the callback of the method is handling the object... The callback of a method is not the method itself...

Last but not least... You can write code with your hands tided around your back blindfolded in a random PL. Does that make it efficient? is it good?

Doubt can be a very important quality indeed, but I don't think here is the case. You are working with something that has been written already, what can you doubt here?

If you install a new package or start working with a new library, you start coding in the dark? Doesn't the documentation come in the first place?