【问题标题】:How can i find out the last entered object in an array of objects, where similar objects can be entered multiple times如何在对象数组中找出最后输入的对象,其中可以多次输入类似的对象
【发布时间】:2019-01-22 05:48:21
【问题描述】:

假设, 我有一个带有属性的对象 details : {"name","id"} ,现在有一个包含详细信息集合的数组。现在假设,一个带有{name:max, id:55} 的对象被多次推送到数组中。如何使用 TypeScript 从该数组中找出最后输入的 {name:max,id:55}

【问题讨论】:

  • 数据[data.length-1]

标签: javascript arrays angular typescript object


【解决方案1】:

你可以用纯 JavaScript 和 lastIndexOf:

const myArray = [{
  name: "max",
  id: 55
}, {
  name: "john",
  id: 13
}, {
  name: "susan",
  id: "123"
}, {
  name: "max",
  id: 55
}];

const lastEntered = (name, id) => {
    var matches = myArray.filter(e => e.name == name && e.id == id);
    return matches.length - 1;
}

console.log(lastEntered("max", 55));

【讨论】:

  • 返回-1
  • 抱歉@PrashantZombade,会修复的。
  • 这是错误的。首先,从问题来看,用户想要最后添加的对象,而不是索引。即使您返回索引,考虑到答案代码中显示的示例,它也应该返回 3。最后,在答案标题中,您已写信使用lastIndexOf,但您使用的是filter
【解决方案2】:

数组是后进先出的数据结构。

所以最后一个 in 元素将占据索引最大的元素。

所以你可以通过array[array.length-1]获取元素

【讨论】:

    【解决方案3】:

    您可以使用reduce将数组更改为对象,其中键是对象中的值,值是该键的最后一个索引。

    const details = [{ name: 'max', id: 55 }];
    const detailsMap = details.reduce((acc, person, index) => {
      acc[person.id] = index;
      return acc;
    }, {});
    const lastIndexOfMax = detailsMap[55];
    

    这里我们将detail对象的id设置为key(因为我假设每个id都是唯一的)。当我们将该键输入到详细信息映射中时,它会返回使用该 id 最后所在的数组的索引。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-06-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-05-05
      • 1970-01-01
      • 2021-12-31
      • 1970-01-01
      相关资源
      最近更新 更多