Answer the question
In order to leave comments, you need to log in
How to optimize the for loop with three levels of nesting?
Hello, I'm new so maybe I don't know the obvious. There are two arrays and a loop:
const arr1 = [
[432432, 23423, 123123, 54364346],
[756456, 2423423, 645654, 23423423],
[12354, 123123, 23423423,1235765]
];
const arr3 = [12354, 5345, 53456346];
const arrResult = [];
for (let i = 0; i < arr1.length; ++i) {
for (let j = 0; j < arr1[i].length; ++j) {
for (let k = 0; k < arr3.length; ++k) {
if (arr1[i][j] === arr3[k]) {
arrResult.push(arr1[i][j]);
break;
}
}
}
}
console.log(arrResult);
Answer the question
In order to leave comments, you need to log in
If on the forehead:
const arr1 = [
[ 432432, 23423, 123123, 54364346],
[ 756456, 2423423, 645654, 23423423],
[ 12354, 123123, 23423423, 1235765]
]
const arr3 = [ 12354, 5345, 53456346 ]
const arrResult = arr1
.flat(Infinity)
.filter(el => arr3.includes(el))
console.log(arrResult)
// Array [ 12354 ]
const arr1 = [
[ 432432, 23423, 123123, 54364346],
[ 756456, 2423423, 645654, 23423423],
[ 12354, 123123, 23423423, 1235765]
]
const arr3 = [ 12354, 5345, 53456346 ]
const arr1s = arr1.flat(Infinity)
arr1s.sort((a, b) => a - b)
const arr3s = arr3.slice()
arr3s.sort((a, b) => a - b)
const arrResult = []
for (let i = 0, let j = 0; i < arr1s.length, j < arr3s.length;) {
if (arr1s[i] === arr3s[j]) {
arrResult.push(arr1s[i])
i += 1
} else if (arr1s[i] < arr3s[j]) {
i += 1
} else {
j += 1
}
}
console.log(arrResult)
// Array [ 12354 ]
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question