Many StackOverflow questions on sorting arrays in Javascript, however I could not find a question for this specific use case that involves a second array.
I have the following 2 arrays. One array is the main array of data, and the other array is used to filter + sort the main array:
let sortingArray = ['pts', 'ast', 'reb', 'stl'] let mainArray = [ { key: 'stl', val1: '3', val2: 5 }, { key: 'blk', val1: '5', val2: 1 }, { key: 'pts', val1: '23', val2: 44 }, { key: 'fgm', val1: '11', val2: 15 }, { key: 'ast', val1: '13', val2: 15 }, { key: 'reb', val1: '7', val2: 4 }, ]; // Using the 2 arrays above, I am trying to create the following output let outputArray = [ { key: 'pts', val1: '23', val2: 44 }, { key: 'ast', val1: '13', val2: 15 }, { key: 'reb', val1: '7', val2: 4 }, { key: 'stl', val1: '3', val2: 5 }, ]; // My code so far outputArray = mainArray .filter(row => sortingArray.includes(row.key)) // .sort()
I can filter, however I am not sure how to handle this sort in the best manner. To clarify, I'd like the mainArray
to be sorted based on the order of values in the sortingArray
. I'm sure I could come up with an 5-10 line function that handles the sort using the sortingArray
(via a loop of the array), however it would be great if there was a cleaner, 1-2 line arrow function I could use for this. This way, I would not have to break up the chaining of functions onto the mainArray
.
Any thoughts or help on this would be great! I will update if I come up with an answer in the meanwhile.
Edit: Creating a separate-function to sort the array is quite straightforward:
let outputArray = []; sortingArray.forEach(key => { let obj = mainArray.filter(row => row.key === key)[0]; outputArray.push(obj); });
However an arrow function would still be preferred here.