【问题标题】:Saving into new array all indexes of other array elements which meet condition using .findIndex使用 .findIndex 将满足条件的其他数组元素的所有索引保存到新数组中
【发布时间】:2019-05-24 04:59:02
【问题描述】:
const jumbledNums = [123, 7, 25, 78, 5, 9]; 

const lessThanTen = jumbledNums.findIndex(num => {
  return num < 10;
});

嗨, 我的问题是这个 sn-p 只返回第一个满足条件的元素索引 num &lt; 10 ,但我想将所有满足条件的索引保存到新数组中。根据我在.findIndex() 的Mozilla 文档中阅读的内容,它在找到满足条件的元素后不会检查其他元素。有什么方法可以在数组中的每个元素上重复.findIndex(例如使用.map())还是我需要使用其他方法来做到这一点?

【问题讨论】:

标签: javascript arrays array.prototype.map


【解决方案1】:

使用Array#reduce()

const jumbledNums = [123, 7, 25, 78, 5, 9];

const lessThanTen = jumbledNums.reduce((a, c, i) => (c < 10 ? a.concat(i) : a), [])

console.log(lessThanTen)

【讨论】:

  • 它工作正常,但我不懂代码。您正在按条件 c
【解决方案2】:

您可以首先映射小于十的索引或-1,然后过滤索引数组以获取有效索引。

const
    jumbledNums = [123, 7, 25, 78, 5, 9],
    lessThanTen = jumbledNums
        .map((v, i) => v < 10 ? i : -1)
        .filter(i => i !== -1);

console.log(lessThanTen);

【讨论】:

    【解决方案3】:

    你可以使用array.filter,它会返回一个新的数组来检查条件。获取值

    但是array.filter不返回索引,所以你可以使用array.map,它会创建一个新的数组,你可以使用array.filter去除未定义的情况。

    我希望这能解决问题。

    const jumbledNums = [123, 7, 25, 78, 5, 9]; 
    
    const lessThan10 = jumbledNums.filter(o => o<10)
    
    console.log("array with less than 10", lessThan10)
    
    const lessThan10Indexes = jumbledNums.map((o,i) =>{ 
      return o < 10 ? i : undefined
    }).filter(o => o)
    
    console.log("array with less than 10 Indexes", lessThan10Indexes)

    【讨论】:

    • 预期结果是索引而不是值
    • 零是一个有效的索引,但是是假的。
    • const jumbledNums = [3, 123, 7, 25, 78, 5, 9]; ,为什么 array.filter 是问题。我没有检查那个。我第一次注意到对此有任何想法。那是 array.filter ,过滤虚假值
    猜你喜欢
    • 2018-12-08
    • 2012-01-14
    • 2018-07-26
    • 1970-01-01
    • 2014-11-28
    • 1970-01-01
    • 2017-06-20
    • 1970-01-01
    • 2012-01-07
    相关资源
    最近更新 更多