gpt4 book ai didi

javascript - 例如使用filter()方法,如何同时返回满足条件的元素及其索引值?

转载 作者:行者123 更新时间:2023-12-02 09:03:32 27 4
gpt4 key购买 nike

这里以代码为例:

const nums = [1, 1, 3, 2, 2, 2, 2, 2, 2, 2];

oddArr = arrNum.filter(function(num,index){
return num % 2 != 0
})

evenArr = arrNum.filter(function(num,index){
return num % 2 === 0
})

这里我想返回新数组,其中包含满足条件的每个元素的原始索引。我尝试在条件 (num % 2 === 0) 之后放置 , 但什么也没有

如果要查找赔率数字,我希望得到这样的输出(粗体数据是指原始数组中该数字的索引:[1,0,1,1,3,2]也许为每个结果都得到一个对象会更好。像这样的事情:

[
{1,0},
{1,1},
{3,2}
]

我什至不知道它是否可能,但我想知道因为其他代码有效地工作:

function array_odd_even_position(a) {
return a.filter((num,index) => console.log(num,index));
}

array_odd_even_position([1, 1, 3, 2, 2, 2, 2, 2, 2, 2])

最佳答案

filter 本身在这里没有帮助,因为它总是返回数组的值,而不是其索引。不过,这样就可以了:

oddIndexes = arrNum.map((_, idx) => idx).filter(idx => arrNum[idx] % 2)

首先将数组映射到索引数组,然后过滤它们。您可以使用 reduce 在一次迭代中完成此操作:

oddIndexes = arrNum.reduce((acc, n, idx) => {
if (n % 2) {
acc.push(idx);
}
return acc;
}, []);

关于javascript - 例如使用filter()方法,如何同时返回满足条件的元素及其索引值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61139850/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com