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
You can sort the fields array based on the index value before iterating over it:
You first need to sort your array :
try this :