skip to Main Content

I have a forEach loop that calls a function for each element in the loop. One of the elements is an element called index that has values as such:

"fields": [
                {
                    "label": "ID",
                    "index": 0.0
                },
                {
                    "label": "field 1",
                    "index": 1.0
                },
                {
                    "label": "field 2",
                    "index": 2.0
                },
                {
                    "label": "field 3",
                    "index": 2.7
                }
]

My Code:

const func2 = (result) => {
  result.data.fields.forEach((d) => {
    otherFunc(d.label);
  });
});

const otherFunc = (d) => //do something

As of now otherFunc is being called in any order. Can it be called based on the index field in result from low to high. That is call in the order of ID, field 1, field 2, field 3` instead of a random order.

2

Answers


  1. You can sort the fields array based on the index value before iterating over it:

    ....
    result.data.fields
     .sort((a, b) => a.index - b.index) //sort the fields array based on the index
     .forEach((d) => {
       otherFunc(d.label);
     });
    ....
    
    Login or Signup to reply.
  2. You first need to sort your array :

    try this :

     const func2 = (result) => {
        result.data.fields
      .sort((a, b) => a.index - b.index) // sort by index in ascending order
       .forEach((d) => {
        otherFunc(d.label);
      });
     };
    
     const otherFunc = (d) => {
       // do something
      };
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search