繁体   English   中英

我试图在数字数组上使用.filter、.sort 和.reduce 以返回由逗号和空格分隔的字符串

[英]Im trying to use .filter, .sort, and .reduce on an array of numbers to return a string separated by a comma and a space

我应该写一个 function ,它接受一个数字数组并返回一个字符串。 function 应该使用过滤器、排序和归约来返回一个只包含奇数的字符串,并以逗号分隔升序。

我似乎无法让 my.reduce 方法实际返回任何内容,并且我的 if 条件似乎无法正常工作......(例如,它在最后一个数字的 output 之后添加了一个逗号和空格,例如“3 , 17, ")

这是我到目前为止所做的代码......

 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"

有没有人有时间帮我整理一下我的 reduce 方法? 我尝试传入索引以确定reduce是否在最后一个元素上迭代而不是output最后一个元素之后的“,”......但没有让它工作......另外,我还是不明白为什么我不断得到“未定义”作为我的输出!

谢谢你的帮助!

您可以将检查替换为仅进行加法并且没有起始值。

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

而不是使用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;
}

不改变参数也被认为是一种好习惯。

另一种方法

使用.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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM