【发布时间】:2020-09-03 05:58:15
【问题描述】:
我有一个数组,我想将某些项目始终放在最上面。我从 API 收到如下响应。
const itemInventorylocationTypes = [
{
itemInventorylocationId: '00d3898b-c6f8-43eb-9470-70a11cecbbd7',
itemInventorylocationCd: 'Rummsan'
},
{
itemInventorylocationId: '1e8cd068-3cfc-4e25-af22-4a8fec3c794d',
itemInventorylocationCd: 'Yes'
},
{
itemInventorylocationId: 'f78fb228-7d1a-4cad-bde7-956e5f46db69',
itemInventorylocationCd: 'Rambo'
},
{
itemInventorylocationId: 'ce4a8a4d-a282-424b-bb2a-5a5187db02e0',
itemInventorylocationCd: 'Veronica'
},
{
itemInventorylocationId: '87082949-b148-4766-ad1d-148b91a46a79',
itemInventorylocationCd: 'Hunnumous'
},
{
itemInventorylocationId: '0fdaf8eb-07f4-4300-9c20-44f788724c59',
itemInventorylocationCd: 'PerryPerry'
},
{
itemInventorylocationId: '4f75ed92-68c0-4137-be37-d64ae77653c7',
itemInventorylocationCd: 'Dont know why'
},
{
itemInventorylocationId: '50efa718-6eed-4eff-ad13-305864c1b243',
itemInventorylocationCd: 'Its ok'
},
{
itemInventorylocationId: 'c7d3275b-cad9-45b2-9065-0fefdf7fc241',
itemInventorylocationCd: 'This is some random thing'
}
];
现在我希望Veronica,rambo, Hunnumous,PerryPerry and Rummsan 的元素按此顺序首先出现。
为此,我创建了一个参考数组,然后使用 lodash intersectionWith 和 DifferenceWith 将它们分解。
const referenceArray = ['Veronica', 'Rambo', 'Hunnumous', 'PerryPerry', 'Rummsan'];
export const sortitemInventory = (itemInventorylocationTypes: DropdownOption[]) => {
const commonElements = _.intersectionWith(itemInventorylocationTypes, referenceArray, (x, y) => x.itemInventorylocationCd == y);
const differentElements = _.differenceWith(itemInventorylocationTypes, referenceArray, (x, y) => x.itemInventorylocationCd == y);
console.log(commonElements);
console.log(differentElements);
cosnst newArray = [...commonElements, ...differentElements];
};
预期公共元素按referenceArray 中的顺序排列。但我得到的是,
const itemInventorylocationTypes = [
{
itemInventorylocationId: '00d3898b-c6f8-43eb-9470-70a11cecbbd7',
itemInventorylocationCd: 'Rummsan'
},
{
itemInventorylocationId: 'f78fb228-7d1a-4cad-bde7-956e5f46db69',
itemInventorylocationCd: 'Rambo'
},
{
itemInventorylocationId: 'ce4a8a4d-a282-424b-bb2a-5a5187db02e0',
itemInventorylocationCd: 'Veronica'
},
{
itemInventorylocationId: '87082949-b148-4766-ad1d-148b91a46a79',
itemInventorylocationCd: 'Hunnumous'
},
{
itemInventorylocationId: '0fdaf8eb-07f4-4300-9c20-44f788724c59',
itemInventorylocationCd: 'PerryPerry'
}
];
还有其他方法吗?我可能可以循环每个元素,然后将其推送到新数组,但只是检查是否有更好的方法。
【问题讨论】:
-
intersectionWith将数组的顺序保存在第一个参数中。这就是为什么您需要重新订购您的commonElements。 -
好吧,您可以在将其用作参考之前将
reverse()referenceArray用作参考。 -
@HaoWu,反转referenceArray将只得到带有字符串的数组,而不是带有对象的数组。
标签: javascript reactjs typescript lodash