如何使用键值对获取数组的lastindex

时间:2019-06-05 15:46:27

标签: javascript node.js typescript

我正在尝试从last index的{​​{1}}中获得value的{​​{1}}。

我无法使其工作;我期望array是值为objects的元素lastIndexOf

id
  

类型'0'的参数不能分配给类型'{id:number;名称:字符串;排名:数字;}'。

5 个答案:

答案 0 :(得分:1)

您可以映射到布尔数组:

    var lastIndex =sample.map(s => 
  s.id === 0).lastIndexOf(true);

然后按上一个索引访问数组:

console.log(sample[lastIndex]);

答案 1 :(得分:0)

const lastIndexWithIdZero = this.sample.length - this.sample.reverse().findIndex(i => i.id === 0);
if (lastIndexWithIdZero > arrLen) {
    throw new Error('didn\'t worked');
}

忘记了,它很慢,最好只使用

let lastIndexWithIdZero = -1;
for (let i = 0, v; v = sample[i]; i++) {
    if (v.id === 0) {
        lastIndexWithIdZero = i;
    }
}
console.log(lastIndexWithIdZero);

http://jsben.ch/LY1Q0

答案 2 :(得分:0)

尝试一下:

const lastIndex = sample.map(res=>res.id).lastIndexOf(0) // id = 0 
console.log(lastIndex) // 2

答案 3 :(得分:0)

Array的lastIndexOf方法使用严格相等(===或三重等于运算符使用的相同方法)将searchElement与Array的元素进行比较。如果数组包含对象,则必须使用其他方法。

如果性能并不重要并且数据量不是很大,则可以使用

const lastIndex = sample.length - 1 - sample
                                      .slice()
                                      .reverse()
                                      .findIndex( item => item.id === 0 );

slice将创建该数组的副本,reverse将对其进行反转,findIndex将返回与o.id === 0相匹配的第一项,并从{中减去最终结果{1}}。对于大型数据集,效率不是很高。

或者您可以使用普通的sample.length - 1

for

function findLastIndexOf(arr) { for (let i = arr.length; i--;) { if (arr[i].id === 0) { return i; } } } findLastIndexOf(sample); 看起来很奇怪,但是它将从最后一个位置开始迭代,并在for (let i = arr.length; i--;)达到0值时停止。尝试一下。

希望有帮助

答案 4 :(得分:0)

您可以过滤结果,然后反转结果并获取第一项。

const sample = [{
    id: 0,
    name: "abbay",
    rank: 120
  },
  {
    id: 1,
    name: "sally",
    rank: 12
  },
  {
    id: 0,
    name: "abbay",
    rank: 129
  }
]

console.log(
  sample
    // Add the index to the object
    .map((i, idx) => ({id: i.id, idx}))
    // Filter the object where id == 0
    .filter(i => i.id == 0)
    // Reverse the result and get the first item
    // Get the idx
    .reverse()[0].idx
)

相关问题