Firstly, the Math function could be done within the if() test loop as that would ignore p == q items.

However, for situations such as this, I would suggest that it is more typical to have two loops - the outer loop going from 0 to the penultimate item and the inner loop going from the outer loop's counter+1 to the last item:

for (let i = 0; i < items.length - 1; i++) {
  for (let j = i + 1; j < items.length; j++) {
    // check values at i and j
  )
}

This way, i and j will never be the same and you never need to iterate over the entire array for every instance of i.

Answer from ATD on Stack Overflow
🌐
Reddit
reddit.com › r/javascript › what is the performant alternative to nested for loops in javascript?
r/javascript on Reddit: What is the performant alternative to nested for loops in JavaScript?
July 20, 2017 -

Are nested for loops (in general - for loops) expensive in JavaScript? AFAIK prototype.map() is an alternative to for loop when it comes to code organisation but doesn't do well when memory, speed is taken into account. If for loops are expensive, what could be a performant alternative to nested for loop?

Discussions

javascript - What is the best alternative to nested for loops? - Stack Overflow
I'm trying to optimize this code, which mesures the length of 2 points in space and draws a line if the length is apropiate. The thing is that it is very slow (mainly on smartphone). Is there anyth... More on stackoverflow.com
🌐 stackoverflow.com
performance - Nested For Loops JavaScript - Software Engineering Stack Exchange
I have an app which gets data from the database (MongoDB) in JSON format. The returned data contains nested arrays and I want to access the values in the nested arrays. The returned JSON format looks More on softwareengineering.stackexchange.com
🌐 softwareengineering.stackexchange.com
March 14, 2016
Nested for loops vs forEach and nested filter forEach
The difference is pretty minor, and not something you should really optimize for unless you had done some performance testing and knew that was a particular problem spot in your case. That said, with the advent of for...of in ES6, I do not use forEach much anymore. Either there is a more specific array method available (find, filter, map, etc), or a for...of loop has less boilerplate and is more clear. More on reddit.com
🌐 r/learnjavascript
20
November 22, 2020
javascript - Optimizing a nested for loop over JS array of objects - Code Review Stack Exchange
NOTE: I'm bringing this question up in code review rather than stack overflow since I already have a working solution. I just am looking for ways to do it better. I have two arrays. One is an array... More on codereview.stackexchange.com
🌐 codereview.stackexchange.com
November 2, 2017
🌐
Quora
quora.com › What-are-some-alternatives-of-nested-for-loops
What are some alternatives of nested for loops? - Quora
Answer (1 of 3): You can just simply use normal functions like this. [code]for(int x=1;x
🌐
egghead.io
egghead.io › lessons › javascript-avoid-nested-for-loops-with-generators
Avoid Nested For Loops with Generators | egghead.io
[1:07] You're probably thinking if you would do this traditionally you would have done nested for loops or a solution like that. Whereas with generators, you get a very easy-to-follow syntax which is very obvious what it's doing, and rather than nested for loops you're just using a function inside of a function, which is a very common and natural pattern.
Published   December 20, 2019
🌐
The Coding Walrus
thecodingwalrus.com › js › javascript-for-loop-alternatives-2
Javascript For Loop Alternatives 2 | The Coding Walrus
July 28, 2020 - Find the best alternatives to the use of for loops in JavaScript. See use cases for Array methods map, reduce, and forEach and how the stack up against for loop alternatives.
🌐
CLIMB
climbtheladder.com › 10-javascript-nested-loop-best-practices
10 JavaScript Nested Loop Best Practices - CLIMB
July 16, 2025 - As a result, nested loops can cause ... when possible, developers should use alternative methods such as array methods like map(), filter(), reduce() or forEach()....
Find elsewhere
🌐
CopyProgramming
copyprogramming.com › howto › javascript-alternative-to-nested-for-loops-javascript
An alternative to nested for loops in JavaScript - Javascript
April 21, 2023 - JavaScript ES6: Enhancing Nested For Loops, An Alternative Approach to Using Nested For-loops in Julia, Is there a nested array alternative to Javascript's filter function?, Exploring Options Beyond Nested For-Loops
🌐
Reddit
reddit.com › r/learnjavascript › nested for loops vs foreach and nested filter foreach
r/learnjavascript on Reddit: Nested for loops vs forEach and nested filter forEach
November 22, 2020 -

Personally I find functional programming reads easier than nested for loops and has less room for error during setup:

arr.forEach((value1, indexL1) => {
    const remainingNums = arr.filter((null, i) => indexL1 < i);
    remainingNums.forEach(...)

});

I think this approach is slower though. Is it a lot slower to the point it would be looked down on during an algorithm test? I think no matter what you're dealing with O(n^2) since there is still a nested loop.

🌐
AlgoCademy
algocademy.com › link
Nested Loops in JavaScript | AlgoCademy
Recursion: Sometimes, recursion can be an alternative to nested loops for certain problems.
🌐
GitConnected
levelup.gitconnected.com › stop-using-for-loop-here-are-other-cool-options-46549a4dba97
Stop using for loops, here are other cool options | by Madhavan Nagarajan | Level Up Coding
January 22, 2020 - Array.filter, map, some have the same performance as forEach. These are all marginally slower than for/while loop. Unless you are working on performance-critical functionalities, it should be fine using the above methods.
Top answer
1 of 5
5

As others have already mentioned, Array.prototype.filter() might be the simplest approach (or Array.prototype.reduce() could also be used but would require more conditional logic). It would typically be slower than the nested for loops because it would be adding additional function calls, but for small data sets it typically wouldn't be noticeable. For example, I did a search on Google for "jsperf filter nested loop" and found this jsPerf test.

Using Array.prototype.filter() on A2, pass a callback function that returns true when the value at property value is included in A1 by checking A1.indexOf() for a value greater than -1.

const result = A2.filter(function(o) {
    return A1.indexOf(o.value) > -1;
});

This can be simplified to a single line using an ES-6 arrow function and Array.prototype.includes() (Not supported by IE):

const result = A2.filter(o => A1.includes(o.value));

Try it in this snippet:

var A1  = ["1","2","3","4"];

var A2 = [
    {label:"one", value:"1"},
    {label:"two", value:"2"},
    {label:"three", value:"3"},
    {label:"four", value:"4"},
    {label:"five", value:"5"},
    {label:"six", value:"6"},
];
const result = A2.filter(o => A1.includes(o.value));
console.log('result', result);


If you wanted to use Underscore.js, _.filter() and _.includes() could be used to filter out any object in A2 without a value for the value property contained in A1. Expand the snippet below for a demonstration.

var A1  = ["1","2","3","4"];

var A2 = [
    {label:"one", value:"1"},
    {label:"two", value:"2"},
    {label:"three", value:"3"},
    {label:"four", value:"4"},
    {label:"five", value:"5"},
    {label:"six", value:"6"},
];
const result = _.filter(A2, function(o) { return _.includes(A1, o.value);});
console.log('result', result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>

There is an Underscore helper _.pluck() but that is used to collect a value from each item in a collection at a given property (similar to Array.prototype.map().

Lodash also has the same helpers: _.filter() and _.includes().

var A1  = ["1","2","3","4"];

var A2 = [
    {label:"one", value:"1"},
    {label:"two", value:"2"},
    {label:"three", value:"3"},
    {label:"four", value:"4"},
    {label:"five", value:"5"},
    {label:"six", value:"6"},
];
const result = _.filter(A2, function(o) { return _.includes(A1, o.value);});
console.log('result', result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>

Though some question whether libraries like lodash and underscore are really needed anymore. For a discussion on that, check out this article.

2 of 5
5

You can use some built in functions instead of the for loops.

var result = A2.filter(e => A1.includes(e.value));

I can't say if this is much faster, since those functions still loop through the arrays. You'll have to time this with some large input to test.

Be aware that Internet Explorer doesn't support .includes or arrow functions. IE friendly version:

var result = A2.filter(function(e) {return A1.indexOf(e.value) !== -1});
🌐
freeCodeCamp
freecodecamp.org › news › nesting-for-loops-in-javascript
Nesting For Loops in JavaScript
June 2, 2020 - If you're having trouble understanding freeCodeCamp's Nesting For Loops challenge, don't worry. We got your back. In this problem you have to complete the multiplyAll() function, and takes a multi-dimensional array as an argument. Remember that ...
🌐
Reddit
reddit.com › r/learnprogramming › are there any alternatives to nested loops
r/learnprogramming on Reddit: Are there any alternatives to Nested loops
December 8, 2021 -

My mind blanks as how replace nested loops with a faster and perhaps a less wasteful way? I know they can’t always be replaced but when is a good time to replace them.

I figure this will come with time but does anyone have any general or specific tips, use cases or examples of how to replace loops or improve on this. I feel like this what’s turning good ideas into lame or unimpressive by speed issues.

Been practicing algorithms in c, JavaScript and python for about a year and I seem to constantly get slower solutions when doing leetcode for example. Self taught udemy, books and cs50x.

Ideally I like to refactor and improve a python script I created with interns and others that read 100,000 reviews and creates moods similarity recommendation engine that indexed and sorts by mood but it take 7-8 days to update it. But then I upload csv to database and works in fast. But had times where something went wrong and took 21 days to get a file. But before doing that I like to learn in general so I can make better decisions coding.

🌐
Medium
medium.com › @kaiosilveira › mastering-javascript-arrays-beyond-for-and-foreach-loops-e2ecf9dfe3e
Mastering Javascript Arrays: Beyond “for” and “forEach” loops | by Kaio Silveira | Medium
April 11, 2018 - Mastering Javascript Arrays: Beyond “for” and “forEach” loops This article aims to present and explain some nice new features introduced at ECMAScript 2015 (ES6), the Javascript Language …
🌐
Medium
duncan-mcardle.medium.com › javascript-labels-a-better-way-to-break-out-of-nested-loops-fd2823de5ca1
JavaScript labels (a better way to break out of nested loops) | by Duncan McArdle | Medium
October 9, 2020 - A common problem developers will face is that of how to escape from nested loops. In this post, I’ll be using JavaScript labels to demonstrate how this can be done with a little more control. For starters, I’ll be using this data set for the various examples, if you want to follow along:
🌐
Sololearn
sololearn.com › en › Discuss › 152967 › alternative-for-nested-loop
Alternative for nested loop | Sololearn: Learn to code for FREE!
I think it depends on what you want to do with them, because, lets say you want to store numbers in a bidimensional array, you can use nested loops to reach every single position in the array, that is the easy and short way to do it.