0

I have a multidimensional array that behaves like a spreadsheet. First item it's a column header:

[
    ['A', 'B', 'C', 'D'],
    [ 1 ,  2 ,  3 ,  4 ],
    [ 5 ,  6 ,  7 ,  8 ],
    [...]
]

Order of the "columns" is defined by another array:

['C', 'A', 'D', 'B']

Expected result is:

[
    ['C', 'A', 'D', 'B'],
    [ 3 ,  1 ,  4 ,  2 ],
    [ 7 ,  5 ,  8 ,  6 ],
    [...]
]

Would .map, .splice and .indexOf be the best approach? What about their performance on a 20k+ array?

Thanks!

4
  • 20K+ array, are you kidding? Users will never gonna visit your site if you use this in JS. instead try to use it in server Commented Feb 7, 2017 at 7:06
  • Don't worry. I'm using a library with deferRender for that. Commented Feb 7, 2017 at 7:07
  • Why would .splice() be used? What are current performance results? See jQuery - Can threads/asynchronous be done? Commented Feb 7, 2017 at 7:09
  • why not to use a configuration const instead of altering the array itself. I am sure, when you are using the array, instead of going by order of 0,1,2,3 go for the order that your configuration constant says, something like 2,0,3,1. It just how you understand the order. Commented Feb 7, 2017 at 7:18

1 Answer 1

4

function reorder(data, order) {
  let header = data[0];
  let orderIndex = order.map(i => header.indexOf(i));
  return data.map(row => orderIndex.map(i => row[i]));
}

let data = [
    ['A', 'B', 'C', 'D'],
    [ 1 ,  2 ,  3 ,  4 ],
    [ 5 ,  6 ,  7 ,  8 ],
];

let order = ['C', 'A', 'D', 'B'];

console.log(reorder(data, order));

As for performance... you'll need to test it.

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.