Trung0246 Trung0246 - 1 month ago 6
Javascript Question

How to get indexOf location of a value in nested array in javascript?

Disclaimer: This question is NOT as same as this one.

I have an example of nested array:

var testArray = [
true,
"",
[
1,
{a: 2, b: [3, false]},
[2, []],
null
],
4,
undefined,
[5, "test"],
function() {}
];


How to get indexOf of a value in nested array, like:

testArray.multiIndexOf(null); //Expected result will be [2, 3]


I will explain what is happening here.

First, we break down testArray to this:

var testArrayExplain = [0, 1, [0, 1, [0, 1], 3], 3, 4, [0, 1], 6];


As you can see here, this array is as much same as above: first layer of array have length of 7, then take a look at value at location #2, we will see another array being nested to first one. As you can remember from above, that
null
value have the same exact location as location #3 in array at location #2 of first array

So we will have first layer location then second layer location of null:
[2, 3]
, stored in array sorted from first layer to last layer.

Another example:

var testArrayTwo = [1,[2,3,4],5,[6,[7,8],9,10],11,12];
testArrayTwo.multiIndexOf(6); //return [3, 0]


Optional: If an nested array have two same values, then get location of first value, or an array stored both two location? And if value is not in nested array,
return -1
like indexOf?

Am I asking too much? And is this question is important for future developers?

Answer

You could iterate the array and stop if the wanted item is found. If possible have a look for nested arrays and proceed.

Array.prototype.multiIndexOf = function (value) {
    var result;
    this.some(function iter(path) {
        return function (a, i) {
            if (a === value) {
                result = path.concat(i);                        
                return true;
            };
            return Array.isArray(a) && a.some(iter(path.concat(i)));
        }
    }([]));
    return result;
}

var testArray = [true, "", [1, { a: 2, b: [3, false] }, [2, []], null], 4, undefined, [5, "test"], function () { }];

console.log(testArray.multiIndexOf(null));
console.log([1, [2, 3, 4], 5, [6, [7, 8], 9, 10], 11, 12].multiIndexOf(6));
.as-console-wrapper { max-height: 100% !important; top: 0; }

Comments