1

I have the following array

let requiredFields = ["Given Name", "Surname", "Sex", "Birth Date", "Birth Place"]

I am filtering an input array to only return objects where the x.key value is equal to one of the required values.

let filtered = fields.filter((x) => requiredFields.includes(x.key));

Now how do i sort this filtered array so the objects are in order of the requiredFields array.

x.key refers to a value found in requiredFields.

Kay
  • 17,906
  • 63
  • 162
  • 270

2 Answers2

2

You could add a sorting by taking the index of the elements of requiredFields.

let requiredFields = ["Given Name", "Surname", "Sex", "Birth Date", "Birth Place"],
    filtered = fields
        .filter(({ key }) => requiredFields.includes(key))
        .sort(({ key: a }, { key: b }) =>
            requiredFields.indexOf(a) - requiredFields.indexOf(b));
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
0

You can filter the keys, then sort the results by the indicies found in the required fields.

let fields = [
  "Age", "Birth Date", "Birth Place", "Given Name", "ID", "Sex", "Surname"
].map(field => ({ key: field }));

let filter = [ "Given Name", "Surname", "Sex", "Birth Date", "Birth Place" ];

console.log(filterSort(fields, filter));

function filterSort(data, order) {
  return orderArray(data.filter((x) => order.includes(x.key)), order);
}

// Adapted from: https://stackoverflow.com/a/13518848/1762224
function orderArray(data, order) {
  return data.reduce((result, item, index) => {
    result[order.indexOf(data[index].key)] = data[index];
    return result;
  }, []);
}
.as-console-wrapper { top: 0; max-height: 100% !important; }

Furthermore, you can skip the sorting by mapping the required fields to the appropriate field by its key.

let fields = [
  "Age", "Birth Date", "Birth Place", "Given Name", "ID", "Sex", "Surname"
].map(field => ({ key: field }));

let filter = [ "Given Name", "Surname", "Sex", "Birth Date", "Birth Place", "Location" ];

console.log(filterSort(fields, filter));

function filterSort(data, order) {
  return order.map(o => data.find(x => x.key === o)).filter(x => x != null);
}
.as-console-wrapper { top: 0; max-height: 100% !important; }
Mr. Polywhirl
  • 42,981
  • 12
  • 84
  • 132