Skip to content

Instantly share code, notes, and snippets.

@christopher-talke
Last active June 20, 2019 06:24
Show Gist options
  • Save christopher-talke/4064a22ae20bd3c113daa619cb9fb752 to your computer and use it in GitHub Desktop.
Save christopher-talke/4064a22ae20bd3c113daa619cb9fb752 to your computer and use it in GitHub Desktop.
Future reference for immutable sort for object arrays.
const example_1_input = [
{
name: 'product 1',
order: 4
},
{
name: 'product 2',
order: 3
},
{
name: 'product 3',
order: 2
},
{
name: 'product 4',
order: 1
}
];
// Example 1 - Simple sort, immutable one liner...
const example_1_output = [...example_1_input].sort((a, b) => a.order - b.order);
// Before:
// [ { name: 'product 1', order: 4 },
// { name: 'product 2', order: 3 },
// { name: 'product 3', order: 2 },
// { name: 'product 4', order: 1 } ]
// After:
// [ { name: 'product 4', order: 1 },
// { name: 'product 3', order: 2 },
// { name: 'product 2', order: 3 },
// { name: 'product 1', order: 4 } ]
// Example 2 - Re-ordering again...
const [...example_2_output] = example_1_input;
const example_2_targetProduct = example_2_output.splice(1, 1);
example_2_output.splice(2, 0, ...example_2_targetProduct);
const [...finaloutput] = example_2_output.sort((a, b) => a.order - b.order);
// Data To Rearrange:
// [ { name: 'product 1', order: 4 },
// { name: 'product 3', order: 2 },
// { name: 'product 2', order: 3 },
// { name: 'product 4', order: 1 } ]
// Removed Data:
// [ { name: 'product 2', order: 3 } ]
// After Rearrange:
// [ { name: 'product 1', order: 4 },
// { name: 'product 3', order: 2 },
// { name: 'product 2', order: 3 },
// { name: 'product 4', order: 1 } ]
// After Sort:
// [ { name: 'product 1', order: 4 },
// { name: 'product 3', order: 2 },
// { name: 'product 2', order: 3 },
// { name: 'product 4', order: 1 } ]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment