对数组进行排序以使数组中的特定项排在首位-JavaScript

假设我们有一个像这样的对象数组-

const arr = [

   {flag: trueother: 1},

   {flag: trueother: 2},

   {flag: falseother: 3},

   {flag: trueother: 4},

   {flag: trueother: 5},

   {flag: trueother: 6},

   {flag: falseother: 7}

];

我们需要编写一个JavaScript函数,该函数接受一个这样的数组并根据以下条件对其进行排序-

  • 如果arr.flag === false,则匹配元素将首先放置在数组中,但仅放在之前的匹配元素之后。

  • 不匹配的元素将保持原始顺序。

  • 出现顺序很重要。

因此,对于上述数组,输出应为-

const output = [

   {flag: falseother: 3},

   {flag: falseother: 7},

   {flag: trueother: 1},

   {flag: trueother: 2},

   {flag: trueother: 4},

   {flag: trueother: 5},

   {flag: trueother: 6}

];

示例

以下是代码-

const arr = [

   {flagtrueother1},

   {flagtrueother2},

   {flagfalseother3},

   {flagtrueother4},

   {flagtrueother5},

   {flagtrueother6},

   {flagfalseother7}

];

const sortByFlag = arr => {

   const sorter = (a, b) => {

      if(!a['flag'] && b['flag']){

         return -1;

      };

      if(a['flag'] && !b['flag']){

         return 1;

      }

      return a['other'] - b['other'];

   }

   arr.sort(sorter);

};

sortByFlag(arr);

console.log(arr);

输出结果

这将在控制台上产生以下输出-

[

   { flag: falseother: 3 },

   { flag: falseother: 7 },

   { flag: trueother: 1 },

   { flag: trueother: 2 },

   { flag: trueother: 4 },

   { flag: trueother: 5 },

   { flag: trueother: 6 }

]

以上是 对数组进行排序以使数组中的特定项排在首位-JavaScript 的全部内容, 来源链接: utcz.com/z/341072.html

回到顶部