提供了一个列表
[
{id:'i1',value:'v1'},
{id:'i3',value:'v3'},
{id:'i4',value:'v4'},
{id:'i2',value:'v2'},
{id:'i5',value:'v5'},
]
和另一个订购的ID列表
['i1','i2','i3','i4','i5']
获取
[
{id:'i1',value:'v1'},
{id:'i2',value:'v2'},
{id:'i3',value:'v3'},
{id:'i4',value:'v4'},
{id:'i5',value:'v5'},
]
如何在lodash中做到这一点?
答案 0 :(得分:1)
使用sortBy方法并从iteratee函数返回ID的索引位置
let sortedArray = _.sortBy(input, (v) => order.indexOf(v.id))
其中
input = [
{id:'i1',value:'v1'},
{id:'i3',value:'v3'},
{id:'i4',value:'v4'},
{id:'i2',value:'v2'},
{id:'i5',value:'v5'},
]
order = ['i1','i2','i3','i4','i5']
答案 1 :(得分:0)
将数组转换为键为id
的对象,以实现更好的查找。用实际值替换列表中的每个元素。
边缘情况:两个数组具有相同的元素
const foo = [
{id:'i1',value:'v1'},
{id:'i3',value:'v3'},
{id:'i4',value:'v4'},
{id:'i2',value:'v2'},
{id:'i5',value:'v5'},
];
const ordered = ['i1','i2','i3','i4','i5'];
const fooMap = _.keyBy(f, 'id');
const orderedFoo = ordered.map(id => fooMap[id])
答案 2 :(得分:0)
const arr = ['i1','i2','i3','i4','i5'];
const arrObj = [
{id:'i1',value:'v1'},
{id:'i3',value:'v3'},
{id:'i4',value:'v4'},
{id:'i2',value:'v2'},
{id:'i5',value:'v5'}
]
const sortedArr = [];
_.map(arr, a => sortedArr.push(_.find(arrObj, ['id', a])));
console.log(sortedArr)
答案 3 :(得分:0)
let arr = ['i1','i2','i3','i4','i5'];
let arrObj = [
{id:'i1',value:'v1'},
{id:'i3',value:'v3'},
{id:'i4',value:'v4'},
{id:'i2',value:'v2'},
{id:'i5',value:'v5'}
]
console.table(arrObj);
arr.map(v => {
arrObj.sort( v1 => { return v1.id == v ? true : false} )
})
console.table(arrObj);