在javascript中排序之前排除特定的数组对象

问题描述 投票:1回答:3

我想知道如何exlcude(不删除)特定对象然后在javascript中排序嵌套数组对象,下面是对数组对象进行排序的函数。我需要排除没有amount属性的对象,然后在javascript中对只有金额的对象进行排序并映射对象(需要使用exex 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
javascript jquery html5
3个回答
0
投票

您可以使用filter()创建带/不带属性的数组。然后排序所需的数组。最后concat()他们喜欢以下方式:

let providerList = [{id:"transferwise", amount:"1000"}, {id:"wordlremit", amount:"4000"}, {id:"instarem", amount:"3000"}, {country: "Singapore", scn: "SG"}, {country: "India", scn: "IN"}];

let amount = providerList.filter( item => item.hasOwnProperty('amount')).sort((a,b)=> a.amount - b.amount);
let notAmount = providerList.filter( item => !item.hasOwnProperty('amount'));
var res = notAmount.concat(amount)
console.log(res);

1
投票

您可以先根据每个元素是否具有myList属性将amount过滤为两个列表:

const includesAmount = myList.filter(item => item.hasOwnProperty('amount'));
const excludesAmount = myList.filter(item => !item.hasOwnProperty('amount'));
includesAmount.sort(...)

const finalArray = [...includesAmount, ...excludesAmount];

这使得两次通过myList,但是您可以通过迭代myList并将每个元素推送到其各自的数组来一次完成。


0
投票

我不确定为什么上述答案必须使用hasOwnProperty()

只需检查该属性是否存在,它就更简短,更易读:

sortAndFilterProviders() {
  const noAmountList = myList(item => !item['amount']);
  const amountList = myList(item => item['amount']);

  amountList.sort( (a, b) => {
    const a1 = a.amount, 
    b1 = b.amount;
    if (a1 == b1) {
      return 0;
    };
    return a1 > b1 ? 1 : -1;
   });

   console.log(amountList); // check if it is sorted
   return [... noAmountList, amountList];
 }
© www.soinside.com 2019 - 2024. All rights reserved.