首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在javascript中排序前排除特定数组对象

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

Stack Overflow用户
提问于 2019-03-25 11:55:58
回答 3查看 65关注 0票数 1

我想知道如何删除(而不是移除)特定的对象,然后在javascript中对嵌套数组对象进行排序,下面是对数组对象进行排序的函数。我需要排除没有数量属性的对象,然后在javascript中对只有数量的对象进行排序,并映射对象(需要使用exluded obj和sorted obj)。

代码语言:javascript
复制
this.providerList = [{id:"transferwise", amount:"1000"}, {id:"wordlremit", amount:"4000", {id:"instarem", amount:"3000"}, {country: "Singapore", scn: "SG"}, {country: "India", scn: "IN"}];
代码语言:javascript
复制
 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;
  }
代码语言:javascript
复制
expected output
  country: Singapore, India
  Sorted Amount : Transferwise , Instarem, Worldremit
EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2019-03-25 12:44:12

您可以使用filter()创建带/不带该属性的数组。然后对所需的数组进行排序。最后,以如下方式对它们进行concat()

代码语言:javascript
复制
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);

票数 0
EN

Stack Overflow用户

发布于 2019-03-25 11:59:39

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

代码语言:javascript
复制
const includesAmount = myList.filter(item => item.hasOwnProperty('amount'));
const excludesAmount = myList.filter(item => !item.hasOwnProperty('amount'));
includesAmount.sort(...)

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

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

票数 1
EN

Stack Overflow用户

发布于 2019-03-25 13:00:12

我不确定为什么上面的答案一定要使用hasOwnProperty()

简单地检查该属性是否存在会更短且更具可读性:

代码语言:javascript
复制
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];
 }
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/55331070

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档