When the user chooses the columns to be shown, I would like to follow the order of the original array, for example:
Lets say I have this array of columns from a table:
headers = ['first', 'second', 'third', 'fourth']
I have a function that let my users choose which columns should be displayed
table.selectedHeaders.map((column) => {
return headers.find(header => header.value === column)
})
User selected in order: first, third, and second header… the filter will return this array:
['first', 'third', 'second ']
I want it to be like this:
['first', 'second', 'third']
4
Answers
Before allowing the user to choose the columns, create a mapping of the original headers with their indices
When the user selects the headers, you can sort them based on their original order
it filters the array to contain only the headers while retaining their original orders. Then, any headers from selectedHeaders that were not found in the original headers array are appended to it.
use the .filter() instead of map and return a new array with only the selected headers:
One simple way to solve that is just using
.filter
withselectedUser.includes
as conditional logic like this: