Thursday, May 9, 2024
 Popular · Latest · Hot · Upcoming
89
rated 0 times [  91] [ 2]  / answers: 1 / hits: 17979  / 8 Years ago, tue, july 26, 2016, 12:00:00

I'm trying to calculate the sum of the height of a couple elements in the page using map & reduce. For unknown reasons this is throwing me the following exception:




VM52933:2 Uncaught TypeError: $(...).map(...).reduce is not a
function(…)




$('.items')
.map( (index,slide) => $(slide).height() )
.reduce( (prev, next) => prev + next, 0 )


.map returns a valid array:



[48, 48, 48, 75, 48]


If i do the map separately ( [48, 48, 48, 75, 48].reduce(...) ) it works.
What am I doing wrong here?


More From » jquery

 Answers
30

It is because you are when you do $('.items') its an array like structure but not array. If you see the prototype it dof NodeList type ad it doesn't have reduce method on it. If you pass this from Array.from then it will convert it to proper array and you will be able to apply reduce, map and all the other array functions.



More details can be found at



https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/from



do something like



Array.from($('.items'))
.map( (slide) => $(slide).height() )
.reduce( (prev, next) => prev + next, 0 );

[#61243] Saturday, July 23, 2016, 8 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
sabrina

Total Points: 92
Total Questions: 92
Total Answers: 85

Location: Palestine
Member since Thu, Feb 2, 2023
1 Year ago
;