gpt4 book ai didi

javascript - 通过字符串属性值查找对象数组中最长的字符串

转载 作者:行者123 更新时间:2023-11-30 07:50:13 25 4
gpt4 key购买 nike

我目前有一个如下所示的数组:

var array = [
{
"title": "Ender's Game",
"genre": "Science Fiction",
"year": 2008
},
{
"title": "Harry Potter and the Goblet of Fire",
"genre": "fantasy",
"year": 2002
},
{
"title": "Pride and Predjudice",
"genre": "romance",
"year": 1980
}
]

我想遍历这个数组并找到最长流派的长度。我想要这样的东西:

longestGenre(array);
15

我尝试了一些方法,包括以下内容:

var getLongest = (array, key) =>
{
let r = Object.values(array).reduce((res, curr) =>
{
if (!Array.isArray(curr))
return res;

let newMax = curr.reduce(
(r, c) => c[[key]] && (c[[key]].length > r.length) ? c[[key]] : r,
""
);

res = newMax.length > res.length ? newMax : res;
return res;

}, "");
longest = r;
return longest;
}

我尝试的另一种方法是:

  for (key in obj){
if (!obj.hasOwnProperty(key)) continue;
if (obj.key.length > longest)
longest = obj.key.length;
}

最佳答案

您不需要所有这些检查和嵌套循环,只需将数组映射到流派的长度,然后取最大值:

 const longestGenre = Math.max(...array.map(movie => movie.genre.length));

或动态:

const longest = (key, array) => Math.max(...array.map(it => it[key].length));

console.log(longest("genre", /*in*/ array));

关于javascript - 通过字符串属性值查找对象数组中最长的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54351784/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com