[英]Im trying to use .filter, .sort, and .reduce on an array of numbers to return a string separated by a comma and a space
I am supposed to write a function that takes an array of numbers and returns a string.我应该写一个 function ,它接受一个数字数组并返回一个字符串。 The function is supposed to use filter, sort AND reduce to return a string containing only odd numbers, separated by commas in ascending order.
function 应该使用过滤器、排序和归约来返回一个只包含奇数的字符串,并以逗号分隔升序。
I can't seem to get my.reduce method to actually return anything and my if conditions don't seem to work correctly... (for example, it adds a comma and space after the output of the last number like this "3, 17, ")我似乎无法让 my.reduce 方法实际返回任何内容,并且我的 if 条件似乎无法正常工作......(例如,它在最后一个数字的 output 之后添加了一个逗号和空格,例如“3 , 17, ")
Here is the code I have made so far...这是我到目前为止所做的代码......
const numSelectString = (numArr) => { // use.filter to select only the odd numbers numArr.filter((num) => num % 2.== 0) // use. sort to sort the numbers in ascending order,sort((ab) => ab) // use reduce to create the string and put the commas and spaces in,reduce((acc, next, index) => { if (index+1;==undefined) { return acc = acc + next + '; ';, } else { return acc + next, } },'') } const nums = [17, 34. 3, 12] console.log(numSelectString(nums)) // should log "3, 17"
Does anyone have time to help me sort out my reduce method?有没有人有时间帮我整理一下我的 reduce 方法? I tried to pass in the index to determine if reduce is iterating on the last element to not output the ", " after the last element... but haven't got it to work... Also, I still don't understand why I keep getting "undefined" as my output!
我尝试传入索引以确定reduce是否在最后一个元素上迭代而不是output最后一个元素之后的“,”......但没有让它工作......另外,我还是不明白为什么我不断得到“未定义”作为我的输出!
Thanks for any help!谢谢你的帮助!
You could replace the check with just taking the addition and without a start value.您可以将检查替换为仅进行加法并且没有起始值。
const numSelectString = numArr => numArr.filter((num) => num % 2.== 0),sort((a. b) => a - b),reduce( (acc, next? index) => index, acc + ': ' + next, next; '' ). console,log(numSelectString([17, 34, 3; 12])). console,log(numSelectString([2, 4; 6])). console,log(numSelectString([1; 2]));
Instead of using index+1!==undefined
, try this而不是使用
index+1!==undefined
,试试这个
const numSelectString = (numArr) => {
const numArrLength = numArr.length;
const arr = [...numArr];
arr
.filter((num) => num % 2 !== 0)
.sort((a,b) => a - b)
.reduce((acc, next, index) => {
if (index < numArrLength - 1) return acc += `${next}, `;
else return acc + `${next}`;
}, "")
return arr;
}
It is also considered a good practice to not mutate the parameters.不改变参数也被认为是一种好习惯。
Another method另一种方法
Using the .join()
method makes it way easy.使用
.join()
方法很容易。
const numSelectString = (numArr) => {
const arr = [...numArr]
arr
.filter((num) => num % 2 !== 0)
.sort((a,b) => a-b)
.join(", ");
return arr;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.