简体   繁体   中英

How can I efficiently sort an array of objects in Javascript in different ways?

I have this array of objects:

[{a:5,b:2},{a:10,b:20},{a:1,b:3},{a:8,b:12}]

And I must sort it in different ways. For example for order = 1 the order must be like this:

1.- {a:8,b:12} 2.- {a:10,b:20} 3.- {a:1,b:3} 4.- {a:5,b:2}

If order = 2

1.- {a:10,b:20} 2.- {a:1,b:3} 3.- {a:8,b:12} 4.- {a:5,b:2}

If order = 3

1.- {a:5,b:2} 2.- {a:1,b:3} 3.- {a:8,b:12} 4.- {a:10,b:20}

I know I can create a new array and pushing the elements according the different orders like this

if(order === 1) {
  oldArray.reduce((a, obj) => {
    if (obj.a === 8) {
      newArray.push(obj);
    }
    return a;
  }, []);
  oldArray.reduce((a, obj) => {
     if (obj.a === 10) {
       newArray.push(obj);
     }
        return a;
      }, []);
  }

And so on, is there a way to fix it with fewer lines of code?

You don't need to sort anything, you just have different hardcoded orders. Use

function getArray(order) {
  if (order == 1) {
    return [{a:8,b:12}, {a:10,b:20}, {a:1,b:3}, {a:5,b:2}];
  }
  if (order == 2) {
    return [{a:10,b:20}, {a:1,b:3}, {a:8,b:12}, {a:5,b:2}];
  }
  if (order == 3) {
    return [{a:5,b:2}, {a:1,b:3}, {a:8,b:12}, {a:10,b:20}];
  }
  throw new Error(`unknown order '${order}'`);
}

or if you need to return the same objects every time

const a8b12  = {a:8, b:12};
const a10b20 = {a:10,b:20};
const a1b3   = {a:1, b:3 };
const a5b2   = {a:5, b:2 };
function getArray(order) {
  if (order == 1) {
    return [a8b12, a10b20, a1b3, a5b2];
  }
  if (order == 2) {
    return [a10b20, a1b3, a8b12, a5b2];
  }
  if (order == 3) {
    return [a5b2, a1b3, a8b12, a10b20];
  }
  throw new Error(`unknown order '${order}'`);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM