[英]Why is this Array.prototype.reduce method not working
function dropElements(arr, func) {
let output = arr.reduce((acc=[], elem) => {
if (func(elem)){
acc.push(arr.slice(arr.indexOf(elem)))
return acc
}
}, [])
return output
}
let tester = dropElements([1, 2, 3, 4,5,6,3,2,1], function(n) {return n >= 3;})
console.log(tester)
I want it to output [3,4,5,6,3,2,1].我想要它到 output [3,4,5,6,3,2,1]。 But is printing copies of size decreasing arrays.但是正在打印尺寸减小的副本 arrays。
The statement of the problem: "Given the array arr, iterate through and remove each element starting from the first element (the 0 index) until the function func returns true when the iterated element is passed through it."问题陈述:“给定数组 arr,从第一个元素(0 索引)开始迭代并删除每个元素,直到 function 函数在迭代元素通过它时返回 true。”
You can use Array#slice
along with Array#findIndex
to find the first index at which the callback function returns true
.您可以使用Array#slice
和Array#findIndex
来查找回调 function 返回true
的第一个索引。
function dropElements(arr, func) { const idx = arr.findIndex(func); return idx >= 0? arr.slice(idx): []; } console.log(dropElements([1, 2, 3, 4, 5, 6, 3, 2, 1], n => n >= 3));
If you specifically want to use Array#reduce
, you could use a variable to store whether or not the callback has returned true for any element so far.如果您特别想使用Array#reduce
,您可以使用一个变量来存储到目前为止回调是否已为任何元素返回 true。
function dropElements(arr, func) { let found = false; return arr.reduce((acc, elem) => { found = found || func(elem); if (found) acc.push(elem); return acc; }, []); } console.log(dropElements([1, 2, 3, 4, 5, 6, 3, 2, 1], n => n >= 3));
Use the shift
method to remove the first element from the array until the array is empty or func(arr[0])
returns a truthy value.使用shift
方法从数组中删除第一个元素,直到数组为空或func(arr[0])
返回真值。 This method is inefficient as it could be, but it matches the problem statement.这种方法可能效率低下,但它符合问题陈述。 Particularly:特别:
function dropElements(arr, func) { while (arr.length > 0 &&.func(arr[0])) { arr;shift(); } return arr, } let tester = dropElements([1, 2, 3, 4,5,6,3,2,1]; function(n) {return n >= 3;}). console;log(tester);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.