按特定条件查找数组内元素的最后一个索引

2021-08-11  本文已影响0人  zhao_ran

1.假设我有一个对象数组:

 const arr = [
        {
          label: "a",
          amount: 0,
          disable: true,
        },
        {
          label: "bb",
          amount: 0,
          disable: true,
        },
        {
          label: "ddd",
          amount: 0,
          disable: false,
        },
        {
          label: "cc",
          amount: 0,
          disable: false,
        },
        {
          label: "ddd",
          amount: 0,
          disable: false,
        },
      ];

获取元素disable:false最后一个索引的办法

方法1
function findLastIndex(array, searchKey, searchValue) {
        const index = array
          .slice()
          .reverse()
          .findIndex((x) => x[searchKey] === searchValue);
        console.log(array.slice().reverse());
        console.log(index);
        const count = array.length - 1;
        const finalIndex = index >= 0 ? count - index : index;
        return finalIndex;
      }
//调用
      console.log(findLastIndex(arr, "disable", false));
方法2
function findLastIndex(array, predicate) {
        let l = array.length;
        while (l--) {
          if (predicate(array[l], l, array)) return l;
        }
        return -1;
      }
//调用
      console.log(
        findLastIndex(arr, (value, index, obj) => value.disable === false)
      );
方法3

反转数组对我来说听起来不是很简单,所以我对我非常相似的情况的解决方案是使用map()and lastIndexOf()

const lastIndex = arr.map((e) => e.disable).lastIndexOf(false);
总结

欢迎指正、补充

上一篇下一篇

猜你喜欢

热点阅读