Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
96 views
in Technique[技术] by (71.8m points)

javascript - Why this array.reduce function is not reducing at all? Beginner


I'm beginner to programming/stackoverflow and trying to create a function that sum elements of an array, without the lowest and highest elements.
So I decided to sort the array using ascending order and splice it to remove first and last values. Figured out that this was going to be the easiest way.
But now I have spent literally hours trying to debug it, watched several youtube videos and tried every array.reduce variant I could imagine and find on the internet, trying to under-****ing-stand array.reduce function and why it is not returning reduced array.
Could someone help me? By the way, if someone knows any ways to splice two values from an array without using array.splice two times, I would love to know. Thank you so much.

function sumArray(array) {
  array.sort(function(a,b){return a-b})
  console.log(array) //log1
  array.splice(0, 1)
  array.splice(-1, 1)
  array.reduce(function(a,b){return a+b}, 0);
  console.log(array) //log2
}
question from:https://stackoverflow.com/questions/65886893/why-this-array-reduce-function-is-not-reducing-at-all-beginner

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You are logging the array, not the result of reduce. Assign the result of reduce to a variable and log it, just change the last 2 lines of your function to:

const sum = array.reduce(function(a,b){return a+b}, 0);
console.log(sum) //log2

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...