skip to Main Content

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']

https://jsfiddle.net/w8us9qdb/22

4

Answers


  1. Before allowing the user to choose the columns, create a mapping of the original headers with their indices

    const headers = ['first', 'second', 'third', 'fourth'];
    const headerMap = headers.reduce((map, header, index) => {
      map[header] = index;
      return map;
    }, {});
    

    When the user selects the headers, you can sort them based on their original order

    const selectedHeaders = ['first', 'third', 'second'];
    
    const sortedSelectedHeaders = selectedHeaders.sort((a, b) => {
      return headerMap[a] - headerMap[b];
    });
    
    console.log(sortedSelectedHeaders);
    
    Login or Signup to reply.
  2.   const headers = ['first', 'second', 'third', 'fourth'];
      const selectedHeaders = ['first', 'third', 'second'];
      const properOrderedHeaders = headers
       .filter(header => selectedHeaders.includes(header))
       .concat(selectedHeaders.filter(header => !headers.includes(header)));
    

    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.

    Login or Signup to reply.
  3. use the .filter() instead of map and return a new array with only the selected headers:

    headers.filter((header) => table.selectedHeaders.includes(header));
    
    Login or Signup to reply.
  4. One simple way to solve that is just using .filter with selectedUser.includes as conditional logic like this:

    let headers = ['first', 'second', 'third', 'fourth']
    let selectedUser = ['first', 'third','second']
    let output = headers.filter(h => selectedUser.includes(h));
    console.log(output)
    .as-console-row-code {
      white-space: initial !important;
    }
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search