-1

I want to give a fixed order to an array of javascript objects and I've trying with the answer of this post but they are pointing to the value, not the keys.

fixed_order = ['group','A,'N','R']

data=[
{group: "a", A: 8, N: 6}
{group: "b", N: 4, A: 20, R: 1}
{group: "c", A: 7}
]

I've try with something like this but doesn't work.

data.sort(function (a, b) {
    return fixed_order.indexOf(a.keys()) - fixed_order.indexOf(b.keys());
});

the result shoulb be something like this:

data=[
{group: "a", A: 8, N: 6}
{group: "b", A: 20, N: 4, R: 1}
{group: "c", A: 7}
]
3
  • You cannot guarentee object key order. If you need to force an order, then either use an array, or keep a secondary array with the sorted order that you then use to access the properties in the required order. Commented May 18, 2020 at 19:41
  • It doesn't since it is an alphabetical order Commented May 18, 2020 at 19:43
  • 1
    Don't try to put properties in a certain order. It is an antipattern. Think of objects as an unordered set of properties. Commented May 18, 2020 at 19:44

1 Answer 1

1

You should not attempt to put object properties in a specific order. Objects are better thought of as unordered collections of properties. Even though modern engines implement the order defined by recent EcmaScript specifications, it is not considered good practice to make your code rely on that.

Instead, change your inner data structure from plain objects to arrays. An array is the recommended data structure when order is important.

const fixedOrder = ['group', 'A', 'N', 'R'];

const data = [
    [["group", "a"], ["A", 8], ["N", 6]],
    [["group", "b"], ["N", 4], ["A", 20], ["R", 1]],
    [["A", 7], ["group", "c"]]
];

for (const row of data) { 
    row.sort((a, b) => fixedOrder.indexOf(a[0]) - fixedOrder.indexOf(b[0]));
}

console.log(data);

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.