• 0
Votes
name
name Punditsdkoslkdosdkoskdo

How to nest loops with iterators?

I have the following code:

let array = [0,1,2];
for (let i = 0; i < array>     for (let j = i + 1; j < array>         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;
}

 

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);
  }
}
  • 1
Reply Report