1

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?

6
  • 3
    Is there any rule between order number and the actual order? Or is it like completely custom/random? Commented Jan 13, 2023 at 8:05
  • Specify ordering rules and use array.sort method. Commented Jan 13, 2023 at 8:07
  • @technophyle It is like custom order. There's no relation between order and the elements. Commented Jan 13, 2023 at 8:11
  • 1
    Why do you need to "sort" an oldArray? Does the input ever change? And if yes, in what ways? It sounds like you could simply hardcode a few constants and return the one for respective order. Commented Jan 13, 2023 at 8:15
  • 1
    If it's completely random, you can just return the full array inside a switch-case statement. Commented Jan 13, 2023 at 8:17

1 Answer 1

1

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}'`);
}
Sign up to request clarification or add additional context in comments.

1 Comment

It was like a simple solution, but I was complicating my life. Thanks!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.