-2

Based on this code, I would like to use an arrow function, I am not really used to.. What's the best way to wrote it ?

I would like to keep the same sort order. Since "selectedHeader" is like you can guess, a column variable based on a vue js v-select.

const headers = 
  [ { text: 'City',                  value: 'city'   } 
  , { text: 'Zip code',              value: 'zip'    } 
  , { text: 'Country',               value: 'country'} 
  , { text: 'Number of Inhabitants', value: 'inhabitants' } 
  ];

const selectedHeaders = 
  [ { text: 'City',     value: 'city' } 
  , { text: 'Zip code', value: 'zip'  } 
  ];
  
let tab = [];

for (i = 0; i < headers.length; i++) {
  pos = selectedHeaders.map(function(e) {
    return e.value;
  }).indexOf(headers[i].value);
  if (pos > -1) {
    tab.push(headers[i]);
  }
}

console.log(tab);
Zabz
  • 59
  • 9

1 Answers1

1

If you want to use arrow functions, you can use filter

    const headers = [ { "text": "City", "value": "city" }, { "text": "Zip code", "value": "zip" },{ "text": "Country", "value": "country" },{ "text": "Number of Inhabitants", "value": "inhabitants" }];
    const selectedHeaders = [ { "text": "City", "value": "city" }, { "text": "Zip code", "value": "zip" }];
    let tab =[];
    
    const selectedValues = selectedHeaders.map(header => header.value);
    tab = headers.filter(header => selectedValues.includes(header.value));
    console.log(tab);
Pedro Blandim
  • 385
  • 3
  • 7
  • Thanks you, that's exactly what I was looking for. I am going to try to understand it as much as I can. – Zabz Nov 02 '21 at 14:08