gpt4 book ai didi

javascript - Angular 2,查找数组中接下来的几个元素

转载 作者:行者123 更新时间:2023-12-01 00:27:24 26 4
gpt4 key购买 nike

我的 Angular 2 应用程序中有一组对象。我需要获取数组中接下来的五个元素,其键值大于我传递的键值。

If I pass key = 1, should return values with keys [2,3,4,5,6]
If I pass key = 2, should return values with keys [3,4,5,6,7]
If I pass key = 10, should return values with keys [11,12,13,14]
If I pass key = 12, should return values with keys [13,14]

[
{key: "1", value: "value1"}
{key: "2", value: "value2"}
{key: "3", value: "value3"}
{key: "4", value: "value4"}
{key: "5", value: "value5"}
{key: "6", value: "value6"}
{key: "7", value: "value7"}
{key: "8", value: "value8"}
{key: "9", value: "value9"}
{key: "10", value: "value10"}
{key: "11", value: "value11"}
{key: "12", value: "value12"}
{key: "13", value: "value13"}
{key: "14", value: "value14"}
]

最佳答案

var data = [
{key: "1", value: "value1"},
{key: "2", value: "value2"},
{key: "3", value: "value3"},
{key: "4", value: "value4"},
{key: "5", value: "value5"},
{key: "6", value: "value6"},
{key: "7", value: "value7"},
{key: "8", value: "value8"},
{key: "9", value: "value9"},
{key: "10", value: "value10"},
{key: "11", value: "value11"},
{key: "12", value: "value12"},
{key: "13", value: "value13"},
{key: "14", value: "value14"}
]

getNextFive = (key) => {
const index = data.findIndex(obj => obj.key == key); // no type checking
if (index > -1) { // if key exists in data
return data.slice(index + 1, index + 6).map(val => parseInt(val.key))
} else { // if key doesnt exist in data
return []
}
}

console.log(getNextFive(1));
console.log(getNextFive(2));
console.log(getNextFive(10));
console.log(getNextFive(12));

关于javascript - Angular 2,查找数组中接下来的几个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58863292/

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