RaphaMex
RaphaMex

Reputation: 2839

How to nest loops with iterators?

I have the following code:

let array = [0,1,2];
for (let i = 0; i < array.length; i++)
    for (let j = i + 1; j < array.length; j++) // j starts at i+1
        console.log(array[i], array[j]);

But because of duplicate items, I decided to convert my array to a map. Now I would like to iterate as above on the map:

let map = array.reduce(countIntoMap, new Map());
for (let [i,counti] of map.entries())
    for (let [j,countj] of map.entries()) // j starts at 0
        console.log(array[i], array[j]);

How could I start looping from i + 1?


EDIT: here is the function that counts, because I want to know how many occurrences of each element are there.

function countIntoMap (map, element) {
    if ( ! map.has(element) )
        map.set(element, 1);
    else
        map.set(element, map.get(element) + 1);
    return map;
}

Upvotes: -1

Views: 93

Answers (2)

trincot
trincot

Reputation: 350961

Iterators are not indexable. They have just one way to be iterated, and that is from the start.

However, ECMAScript 2025 makes it easier to skip over the first few elements yielded by an iterator, with drop:

const countIntoMap = (map, element) =>
    map.set(element, (map.get(element) ?? 0) + 1);

const array = [4, 1, 2, 4, 3, 2, 3, 4, 2];

const map = array.reduce(countIntoMap, new Map());

let k = 0; // how many items to drop in the inner loop
for (let [i,counti] of map.entries())
    for (let [j,countj] of map.entries().drop(++k))
        console.log(i, j);

Upvotes: 0

Hikmat G.
Hikmat G.

Reputation: 2621

This will create array of {key, count} objects and it can be iterated as you wanted

let array = [0, 1, 2, 2];

const uniq = array.reduce((acc, a) => {

  let idx = acc.findIndex(b => b.key === a);
  idx === -1 ? acc.push({ key: a, count: 1}) : ++acc[idx].count;
  return acc;

}, []);


for (let i = 0; i < uniq.length; ++i) {
  for (let j = i + 1; j < uniq.length; ++j) {
    console.log(uniq[i].count, uniq[j].count);
  }
}

Upvotes: 1

Related Questions