-2

I have an array of JavaScript objects, smth like this:

const employe = [{
    id: 1,
    age: 22,
    sex: 'Male',
  },
  {
    id: 2,
    age: 23,
    sex: 'Female',
  },
  {
    id: 3,
    age: 33,
    sex: 'Male',
  }
]

I want to sort them based on object key: for example: function sort(age, sex) and i get array:

[22, 23, 33, 'male', 'female', 'male']

I try to do smth like this:

function filterArr(arr, category) {
  let res = {};
  for (let key in arr) {
    if (arr[key].category == category)
      res[key] = arr[key];
  }
  return res;
}
SMAKSS
  • 9,606
  • 3
  • 19
  • 34
SashaQ
  • 1
  • Looks more like a mapping than a sorting to me: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map – Sirko Apr 18 '20 at 12:25
  • `sort()` has two parameters but only "sorts" for `age` (if at all because the example input is already sorted). Are the parameters of `sort()` not relevant for sorting? – Andreas Apr 18 '20 at 12:41

2 Answers2

1

You could iterate the wanted keys, map the value and get a flat result.

const
    getParts = (array, keys) => keys.flatMap(k => array.map(o => o[k])),
    employees = [{ id: 1, age: 22, sex: 'Male' }, { id: 2, age: 23, sex: 'Female' }, { id: 3, age: 33, sex: 'Male' }];

console.log(getParts(employees, ['age', 'sex']));
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
0

you could first sort your array (inspired from How to sort 2 dimensional array by column value?) and then return the wanted fields :

const employe = [
    {
        id: 1,
        age: 22,
        sex: 'Male',
    },
    {
        id: 2,
        age: 23,
        sex: 'Female',
    },
    {
        id: 3,
        age: 33,
        sex: 'Male',
    }];

const sortEmploye = employe.sort(sortFunction);
console.log(returnWantedFields(sortEmploye));

function returnWantedFields(arr){
    const returnedArr = [];
    for (let i=0; i<arr.length; i++){
        returnedArr.push(arr[i]['age']);
    }
    for (let i=0; i<arr.length; i++){
        returnedArr.push(arr[i]['sex']);
    }
    return returnedArr;

}

function sortFunction(a, b) {
    if (a[0] === b[0]) {
        return 0;
    }
    else {
        return (a[0] < b[0]) ? -1 : 1;
    }
}
pragmethik
  • 182
  • 1
  • 7