gpt4 book ai didi

javascript - 搜索数组的函数

转载 作者:行者123 更新时间:2023-12-02 20:34:03 24 4
gpt4 key购买 nike

如何在嵌套数组中搜索元素。以下是数组的样子

arr = [
["choice1", ['a', [2, 4]], ['b', [1, 3, 4]], ['c', [3, 4]]],
["choice2", ['b', [1, 4]], ['c', [1, 3]]],
["choice3", ['b', [1, 2, 4]], ['c', [1, 2, 3, 4]]]
]

如果“a”等于“2”,则以下函数必须在“结果”中返回“choice1”和“choice3”:

function arraySearch(arr, a) {
var result = [];
for(var i = 0; i < arr.length; i++) {
// compare each arr[i] with 'a' for the very first occurrence, and move the next array
if(arr[i].search(a)){
result.concat(arr[0]);
}
}
return result;
}

请帮忙。非常感谢。

最佳答案

类似的东西

arr = [
["choice1", ['a', [2, 4]], ['b', [1, 3, 4]], ['c', [3, 4]]],
["choice2", ['b', [1, 4]], ['c', [1, 3]]],
["choice3", ['b', [1, 2, 4]], ['c', [1, 2, 3, 4]]]
];

find = function(arr, a) {

var found = [];
var foundCurrent;

// for each 'choice'
for (var choice = 0; choice < arr.length; choice++) {
foundCurrent = false;

// look at each entry in the array that is arr[current][1]
for (var entry = 1; entry < arr[choice].length; entry++) {
// search these for the value
if (arr[choice][entry][1].indexOf(a) != -1) {
if (!foundCurrent) {
found[found.length] = arr[choice][0];
}
foundCurrent = true;
}
}
}
return found;
};


find(arr, 2);
>> [choice1, choice3]

关于javascript - 搜索数组的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3595960/

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