0

In my code I have 6 lists of objects of different sizes.

I need to go through them all in a specific order, from the smallest list to the largest.

var list_1 = [...]    // length 24
var list_2 = [...]    // length 4
var list_3 = [...]    // length 3
var list_4 = [...]    // length 4
var list_5 = [...]    // length 11
var list_6 = [...]    // length 2

// Need code here for loop each list in order asc
list_6.forEach(...)   // length 2
list_3.forEach(...)   // length 3
list_2.forEach(...)   // length 4
list_4.forEach(...)   // length 4
list_5.forEach(...)   // length 11
list_1.forEach(...)   // length 24

Does anyone have a simple solution ? Thanks

1
  • 2
    Add the lists to a list and sort that list by the length of its elements. Commented Oct 19, 2020 at 14:40

2 Answers 2

6

You could add the lists in an array, sort it and perform the loop

[list, list2, ...]
    .sort((a, b) => a.length - b.length)
    .forEach(array => array.forEach(...))
0
1

Put the lists into another list and sort them.

const list1 = [1, 2, 3, 4],
  list2 = [1],
  list3 = [1, 2, 3, 4, 5, 6, 7];

let listOfLists = [list1, list2, list3].sort((a, b) => a.length - b.length);

console.log(listOfLists);
listOfLists.forEach(list => {
  list.forEach(itemInList => {
    console.log(itemInList);
  });
});

See StackBlitz example.

3
  • You can post the code here and create a runnable snippet. If the external link is deleted or modified, the answer will have no future value
    – adiga
    Commented Oct 19, 2020 at 14:52
  • Also [this.list1, this.list2, this.list3].sort() is wrong and doesn't work
    – adiga
    Commented Oct 19, 2020 at 14:52
  • You are right, I was too hasty. I've updated the example!
    – Marek W
    Commented Oct 19, 2020 at 14:57

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.