I am supposed to write a function that takes an array of numbers and returns a string. The function is supposed to use filter, sort AND reduce to return a string containing only odd numbers, separated by commas in ascending order.
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, ")
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((a,b) => a-b)
// 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"
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
Does anyone have time to help me sort out my reduce method? 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!
Thanks for any help!
CodePudding user response:
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]));
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
CodePudding user response:
Instead of using index 1!==undefined
, try this
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.
const numSelectString = (numArr) => {
const arr = [...numArr]
arr
.filter((num) => num % 2 !== 0)
.sort((a,b) => a-b)
.join(", ");
return arr;
}