gpt4 book ai didi

javascript - 根据数组索引对查询结果进行排序

转载 作者:行者123 更新时间:2023-11-27 23:34:40 25 4
gpt4 key购买 nike

我有来自anotherCollection的id数组..在我做了很多计算之后,我得到了:

idSortByRank = ["cxwMoC3k6kpf4mr5o","HFYjC5nuT9hKhdyFC","GiM7NCLjck6Pet8Wm"]

我需要从 MyCollection 的 mongodb 集合中返回按 idSortByRank 排序/索引的对象,如下所示:

//expected result should index/sort the same as idSortByRank

[
{"_id": "cxwMoC3k6kpf4mr5o", other field},
{"_id": "HFYjC5nuT9hKhdyFC", other field},
{"_id": "GiM7NCLjck6Pet8Wm", other field}
]

我这样做了,但没有按预期排序:

MyCollection.find({_id:{$in:idSortByRank}});

我的 MyCollection 中没有 rank 字段

非常感谢您...

最佳答案

您可以使用给定数组的索引idSortByRank进行排序。

var idSortByRank = ["cxwMoC3k6kpf4mr5o", "HFYjC5nuT9hKhdyFC", "GiM7NCLjck6Pet8Wm"],
data = [{ "_id": "GiM7NCLjck6Pet8Wm" }, { "_id": "HFYjC5nuT9hKhdyFC" }, { "_id": "cxwMoC3k6kpf4mr5o" }];

data.sort(function (a, b) {
return idSortByRank.indexOf(a._id) - idSortByRank.indexOf(b._id);
});
document.write('<pre>' + JSON.stringify(data, 0, 4) + '</pre>');

关于javascript - 根据数组索引对查询结果进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34221855/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com