[英]Sort array of object based on another string array
I have 2 arrays我有 2 个 arrays
a = [
{ label:"Price", value:10 },
{ label:"Active", value:false },
{ label:"Category", value:"food" },
{ label:"Remarks", value:"none" }
];
b = ["Active","Category","Price"];
How do I sort a according to the order of b?如何根据b的顺序对a进行排序? Can I use ramda?我可以使用 ramda 吗?
Something succinct like the following would be ideal像下面这样简洁的东西是理想的
R.sortBy(R.pipe(R.prop('label'), R.indexOf(R.__, a)))(b);
Similar to this issue, except I don't have index, so I cannot use indexOf method.类似于这个问题,除了我没有索引,所以我不能使用 indexOf 方法。
Sort an array of objects based on another array of ids 根据另一个 id 数组对对象数组进行排序
Appreciate your help!感谢你的帮助!
There might be a more succinct option but here is how I'd do it.可能有一个更简洁的选择,但这是我的做法。
const list = [ {label:"Price", value:10}, {label:"Active", value:false}, {label:"Category", value:"food"}, {label:"Remarks", value:"none"} ]; const labels = ["Active","Category","Price"]; const sorted = list.sort((a, b) => { const aIndex = labels.indexOf(a.label); const bIndex = labels.indexOf(b.label); return aIndex - bIndex; }); console.log(sorted);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.