Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
339 views
in Technique[技术] by (71.8m points)

根据数组中的值 排序对象

var a = [100,200,300]

var b = [{id:'100',name:'小红'},{id:'300',name:'小明'},{id:'200',name:'小蓝'}]


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
var a = [100,200,300];
var b = [{id:'100',name:'小红'},{id:'300',name:'小明'},{id:'200',name:'小蓝'}];

var result = b.sort((aa, bb) => (a.indexOf(aa.id - 0) - a.indexOf(bb.id - 0)));

// 不考虑重复ID的话方法还有很多:
result = a.map(el_a=>(b.find(el_b => el_b.id == el_a)));
result = b.reduce((acc,cur) => (acc[a.indexOf(cur.id - 0)] = cur, acc), []);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...