【问题标题】:Find the longest string from an array of objects in JavaScript从 JavaScript 中的对象数组中查找最长的字符串
【发布时间】:2022-12-03 04:48:18
【问题描述】:

我有一个名为 rows 的对象数组,其中每个对象都有一个名为 name 的字符串属性。

我想得到最长的name。我如何过滤rows并获取名称最长的行,或者获取名称本身。谢谢!

Lodash 或 vanilla JS 都适合我的目的。如果有 2 根绳子的长度最长,则抓住任何一根绳子都适合我的目的。

【问题讨论】:

  • 按长度排序然后抓取第一个?

标签: javascript lodash


【解决方案1】:

只需使用Array.prototype.reduce 并保留最长的字符串。

rows.reduce((longest, current) => longest.name.length > current.name.length ? longest : current);

【讨论】:

  • 这是一个很好的解决方案,但如果有人问这个问题,我建议他们是初学者,您可能不应该介绍 reduce
  • 关于这一点,这是 explanation of reduce 的另一个答案
【解决方案2】:

这应该工作得很好:

rows.sort((x,y) => y.name.length - x.name.length)[0]

这将改变数据。如果您不想对原始的rows 数组进行排序,您可以复制它。但是请注意不要改变任何返回的对象,因为这也会改变原始对象。如果你不想那样,那么你需要做一个深拷贝。

例如,

const rows = [{name: 'abcde'}, {name: 'abc'}, {name: 'abcd'}];

// spreading rows will essentially make a copy of `rows`    
const result = [...rows].sort((x,y) => y.name.length - x.name.length)[0]

console.log(result); // this will print `{name: 'abcde'}`

result.name = 123; // mutating the resulting object after making a copy

console.log(rows); // this will be mutated now

slice()concat() 相同。他们也会制作一个浅拷贝。

【讨论】:

    【解决方案3】:

    const rows = [
      {
        name: "bar",
      },
      {
        name: "foobar",
      },
      {
        name: "ba",
      },
    ];
    
    const firstItem = rows
      .slice()
      .sort((a, b) => (a.name.length > b.name.length ? -1 : 1))[0];
    
    console.log(firstItem.name); // Outputs 'foobar'

    笔记:我正在对数组进行切片以避免就地改变它

    【讨论】:

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