英文:
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
};
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论