D
D
Demarkpro2020-05-11 02:19:34
JavaScript
Demarkpro, 2020-05-11 02:19:34

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);


Since the first array can have quite a lot of values, from 500,000, I would like to know if I can somehow optimize this whole thing? Because now it takes quite a long time. Thanks in advance

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
Rsa97, 2020-05-11
@Demarkpro

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 ]

If you optimize for time, at the expense of memory:
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 ]

True, in both cases it is necessary to look at the behavior in the presence of duplicates in each of the arrays.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question