在循环内按值顺序运行forEach。

huangapple go评论61阅读模式
英文:

Run forEach in order of value inside of loop

问题

我有一个forEach循环,它对循环中的每个元素调用一个函数。其中一个元素是一个名为index的元素,其值如下:

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

我的代码:

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

const otherFunc = (d) => //做一些操作

目前,otherFunc以任意顺序被调用。是否可以根据result中的index字段从低到高的顺序调用它。也就是按照ID, field 1, field 2, field 3的顺序调用,而不是随机顺序。

英文:

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.

答案1

得分: 3

你可以在迭代之前根据 index 值对 fields 数组进行排序:

....
result.data.fields
 .sort((a, b) => a.index - b.index) // 根据索引值对 fields 数组进行排序
 .forEach((d) => {
   otherFunc(d.label);
 });
....
英文:

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);
 });
....

答案2

得分: 2

你首先需要对数组进行排序:

尝试这样做:

 const func2 = (result) => {
    result.data.fields
  .sort((a, b) => a.index - b.index) // 按索引升序排序
   .forEach((d) => {
    otherFunc(d.label);
  });
 };

 const otherFunc = (d) => {
   // 做一些事情
  };
英文:

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
  };

huangapple
  • 本文由 发表于 2023年5月11日 11:56:49
  • 转载请务必保留本文链接:https://go.coder-hub.com/76224054.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定