我想知道如何排除(而不是删除)特定对象,然后在 javascript 中对嵌套数组对象进行排序, 下面的函数对数组对象进行排序。我需要排除没有 amount 属性的对象,然后在 javascript 中对只有 amount 属性的对象进行排序并映射对象(需要使用 exluded obj 和 sorted obj)。
this.providerList = [{id:"transferwise", amount:"1000"}, {id:"wordlremit", amount:"4000", {id:"instarem", amount:"3000"}, {country: "Singapore", scn: "SG"}, {country: "India", scn: "IN"}];
sortAndFilterProviders() {
let myList = [];
myList = [...this.providerList];
myList.push.apply(myList, this.apiproviderdata.apiproviders);
// var mergeList = myList.concat(this.query);
// console.log(mergeList);
myList.sort(function (a, b) {
var a1 = a.amount, b1 = b.amount;
if (a1 == b1) return 0;
return a1 > b1 ? 1 : -1;
});
this.providerList = [...myList];
return this.providerList;
}
expected output
country: Singapore, India
Sorted Amount : Transferwise , Instarem, Worldremit
最佳答案
您可以先根据每个元素是否具有amount
属性,将myList
过滤成两个列表:
const includesAmount = myList.filter(item => item.hasOwnProperty('amount'));
const excludesAmount = myList.filter(item => !item.hasOwnProperty('amount'));
includesAmount.sort(...)
const finalArray = [...includesAmount, ...excludesAmount];
这会两次遍历 myList
,但您可以通过遍历 myList
并将每个元素推送到其各自的数组来一次完成。
关于javascript - 在javascript中排序之前排除特定的数组对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55331070/