简体   繁体   English

如何从嵌套数组中获取项目的索引

[英]How to get index of an item from nested array

如何从嵌套数组中获取项目的索引但不知道嵌套的深度,例如 arr=[a,[b,[c],[d],e],f,[g],h]

For getting the full path, you might use an iterative and recursive approach for the nested array.为了获得完整路径,您可以对嵌套数组使用迭代和递归方法。

The result is an array with all indices.结果是一个包含所有索引的数组。

 function findPath(array, value) { var path = []; array.some(function iter(p) { return function (a, i) { if (a === value) { path = p.concat(i); return true; } if (Array.isArray(a)) { return a.some(iter(p.concat(i))); }; }; }([])); return path; } var array = ['a', ['b', ['c'], ['d'], 'e'], 'f', ['g'], 'h']; console.log(findPath(array, 'a')); console.log(findPath(array, 'b')); console.log(findPath(array, 'c')); console.log(findPath(array, 'd')); console.log(findPath(array, 'e')); console.log(findPath(array, 'f')); console.log(findPath(array, 'g')); console.log(findPath(array, 'h'));
 .as-console-wrapper { max-height: 100% !important; top: 0; }

If I understand your question correctly you are trying to get the index of for example value g .如果我正确理解您的问题,您正在尝试获取例如值gindex

I created a little script that iterates trough the array, and possibly nested arrays, and if found the correct value returns the index .我创建了一个小脚本,它遍历数组和可能的嵌套数组,如果找到正确的value返回index

Here is a screenshot of the array with the keys that the function getIndexOfValue returns.这是带有函数getIndexOfValue返回的键的数组的屏幕截图。

在此处输入图片说明

 var arr = [ "a", [ "b", [ "c" ], [ "d" ], "e" ], "f", [ "g" ], "h" ] function getIndexOfValue(haystack, needle) { for(i in haystack) { if(haystack[i] instanceof Array) { result = getIndexOfValue(haystack[i], needle); if(result) { return result; } } else if(haystack[i] == needle) { return i; } } return false; } var indexOfA = getIndexOfValue(arr, "a"); var indexOfB = getIndexOfValue(arr, "b"); var indexOfC = getIndexOfValue(arr, "c"); var indexOfD = getIndexOfValue(arr, "d"); var indexOfE = getIndexOfValue(arr, "e"); var indexOfF = getIndexOfValue(arr, "f"); var indexOfG = getIndexOfValue(arr, "g"); var indexOfH = getIndexOfValue(arr, "h"); console.log(indexOfA); //0 console.log(indexOfB); //0 console.log(indexOfC); //0 console.log(indexOfD); //0 console.log(indexOfE); //3 console.log(indexOfF); //2 console.log(indexOfG); //0 console.log(indexOfH); //4

It might still contain bugs, I created this quickly in a few minutes.它可能仍然包含错误,我在几分钟内快速创建了它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM