array.find()返回项目和索引

时间:2018-09-05 10:20:52

标签: javascript arrays ecmascript-6

我有一个数据数组,我需要从数组中的项目以及结果的索引中返回数据:

下面的代码返回数据,但不返回索引,因此我认为这根本无法正常工作。

请问有人可以建议我如何实现下面的目标吗?

const result = design.data().items.find((e, i, a, arg) => {
  if(e.id === this.props.match.params.item) {
    return {item:e, index: i}
  }
})

3 个答案:

答案 0 :(得分:4)

您可以使用findIndex代替find方法。

const { items } = design.data();
const id = items.findIndex((e) => e.id === this.props.match.params.item);
if (id !== -1) {
  return { item: items[id], index: id };
}

答案 1 :(得分:2)

您可以创建一个简单的使用findIndex的查找方法。如果索引不是-1(找到一个项目),它将返回该项目和索引:

const findWithIndex = (arr, predicate) => {
  const index = arr.findIndex(predicate);
    
  return {
    item: index !== -1 ? arr[index] : null,
    index
  };
};

const arr = [{ id: 1}, { id: 2 }, { id: 3 }];

const result = findWithIndex(arr, ({ id }) => id === 2);

console.log(result);

使用代码示例:

findwithIndex(design.data().items, e => this.props.match.params.item);

答案 2 :(得分:1)

您可以使用Array.findIndex获取元素的索引。然后使用索引可以从数组中获取元素

const items = design.data().items;
const index = items.findIndex(item => item.id === this.props.match.params.item);
console.log(index);  // gives index
console.log(items[index]);  // gives the element