[英]TS 2 arrays, if item from first array exists in second array then append to start of second array
I have 2 lists of objects.我有 2 个对象列表。
One is the list of 'all' objects, the second is the list of 'special' objects.一个是“所有”对象的列表,第二个是“特殊”对象的列表。
The first list contains all objects, including special objects.第一个列表包含所有对象,包括特殊对象。
How do I sort my list of 'all' objects, to order the objects in the following fashion: First 'special' objects, and then all the rest of the objects?如何对我的“所有”对象列表进行排序,以按以下方式对对象进行排序:首先是“特殊”对象,然后是对象的所有 rest?
Each object has an id.每个 object 都有一个 id。
For example,例如,
List 1:清单 1:
[
{Id: 1, Name: "a", Surname: "a"},
{Id: 2, Name:"b", Surname:"b"},
{Id: 3, Name: "c", Surname: "c"}
]
List 2:清单 2:
[
{Id: 2, Name:"b", Surname:"b"}
]
How do I order it, so the final list is:我如何订购它,所以最终清单是:
[
{Id: 2, Name:"b", Surname:"b"},
{Id: 1, Name: "a", Surname: "a"},
{Id: 3, Name: "c", Surname: "c"}
]
You can use the find
function to check if one of the two compared elements are special and return the result accordingly in a custom sort
function:您可以使用find
function 来检查两个比较元素之一是否特殊,并在自定义sort
function 中相应地返回结果:
let all = [{Id: 1, Name: "a", Surname: "a"}, {Id: 2, Name:"b", Surname:"b"}, {Id: 3, Name: "c", Surname: "c"}]; let special = [{Id: 2, Name:"b", Surname:"b"}]; function sortFunc(a, b) { var s1 = special.find(s=>s.Id==a.Id); var s2 = special.find(s=>s.Id==b.Id); if(s1 && s2) return 0; else if(s1) return -1; else if(s2) return 1; return 0; } let sorted = all.slice().sort(sortFunc); console.log(sorted);
If you are willing to include lodash you can get the result with this如果你愿意包含 lodash,你可以得到这个结果
const List1 = [ {Id: 1, Name: "a", Surname: "a"}, {Id: 2, Name:"b", Surname:"b"}, {Id: 3, Name: "c", Surname: "c"} ] const List2 = [ {Id: 2, Name:"b", Surname:"b"} ] const SpecialIds = _.map(List2, (v) => { return v.Id }) const List3 = _.sortBy(_.map(List1, (v) => { return _.merge({}, v, {...v, Type: _.indexOf(SpecialIds, v.Id) === -1? '1_Normal': '0_Special' }) }), ['Type', 'Id']) console.log(List3)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.min.js"></script>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.