Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Finding the index position of an array inside an array JavaScript
When working with arrays of arrays in JavaScript, you might need to find the index position of a specific sub-array within the main array. This is useful for checking if a particular array exists and determining its location.
Suppose we have an array of arrays like this:
const arr = [ [1,0], [0,1], [0,0] ];
We need to write a JavaScript function that takes an array of arrays as the first argument and a target array as the second argument. The function should return the index position of the target array if it exists, or -1 if it doesn't.
Using Array Methods with Helper Function
const arr = [ [1,0], [0,1], [0,0] ];
const sub = [0, 0];
const matchEvery = (arr, ind, sub) => arr[ind].every((el, i) => el == sub[i]);
const searchForArray = (arr = [], sub = []) => {
let ind = -1;
let { length: len } = arr;
while (len--) {
if (arr[len].length === sub.length && matchEvery(arr, len, sub)) {
ind = len;
break;
}
}
return ind;
};
console.log(searchForArray(arr, sub));
2
Using findIndex() Method
A more modern and concise approach uses the findIndex() method:
const arr = [ [1,0], [0,1], [0,0] ];
const sub = [0, 0];
const findArrayIndex = (arr, target) => {
return arr.findIndex(subArray =>
subArray.length === target.length &&
subArray.every((val, index) => val === target[index])
);
};
console.log(findArrayIndex(arr, sub));
console.log(findArrayIndex(arr, [1, 0]));
console.log(findArrayIndex(arr, [2, 3])); // Not found
2 0 -1
Using JSON.stringify() for Simple Arrays
For arrays containing only primitive values, you can use JSON.stringify() for comparison:
const arr = [ [1,0], [0,1], [0,0] ];
const sub = [0, 0];
const findIndexWithStringify = (arr, target) => {
const targetString = JSON.stringify(target);
return arr.findIndex(subArray => JSON.stringify(subArray) === targetString);
};
console.log(findIndexWithStringify(arr, sub));
console.log(findIndexWithStringify(arr, [0, 1]));
2 1
Comparison of Methods
| Method | Performance | Readability | Limitations |
|---|---|---|---|
| While loop with helper | Fast | Moderate | More verbose |
| findIndex() with every() | Good | High | None for primitive arrays |
| JSON.stringify() | Slower | High | Order-sensitive, primitives only |
Conclusion
The findIndex() method with every() provides the best balance of readability and performance for finding array indices. Use JSON.stringify() only for simple primitive arrays where order matters.
