json 根据作为第二个参数传递的employees属性对所有雇员进行排序

dfuffjeb  于 2023-01-06  发布在  其他
关注(0)|答案(3)|浏览(91)

在这里,我必须创建一个有两个参数的函数,一个是employee数组,另一个是属性数组,它返回根据作为第二个参数传递的employee属性排序的所有员工。

function compare(arr, name){
    
}
let arr = [ 
    {name :"om", age:45},
    {name :"guru", age:95},
    {name :"subh", age:25},                       
    {name :"rahul", age:22},
    {name :"raju", age:35},                        
    ];

 //// output should be array either sorted by name or age
2izufjch

2izufjch1#

javascript内置的数组sort()函数有一个参数可以传入你自己的compare函数中,这个函数会比较数组中的两个不同的值,并根据对compare函数的调用来确定它们的位置。ab。通过传入一个比较函数,您可以准确地指定要比较的对象的属性。在您的情况下,可以使用

function compare(arr, name){
    return arr.sort((a, b) => a[name] - b[name]);
}
let arr = [ 
    {name :"om", age:45},
    {name :"guru", age:95},
    {name :"subh", age:25},                       
    {name :"rahul", age:22},
    {name :"raju", age:35},                        
    ];

Link to more information about the sort() function

o4hqfura

o4hqfura2#

你可以用一个既适用于数字又适用于字符串的函数。

function sort(array, key) {
    return array.sort((a, b) => (a[key] > b[key]) - (a[key] < b[key]));
}

const
    data = [{ name: "om", age: 45 }, { name: "guru", age: 95 }, { name: "subh", age: 25 }, { name: "rahul",  age: 22 }, { name: "raju", age: 35 }];

console.log(sort(data, 'name'));
console.log(sort(data, 'age'));
.as-console-wrapper { max-height: 100% !important; top: 0; }
xjreopfe

xjreopfe3#

你可以有不同的比较函数,并且基于“key”你可以选择使用哪种比较。下面的函数可以扩展到许多键和许多数据类型。(另外,你可以使用另一个参数进行asc或desc)

function sort(arr, key) {
  const numberCompare = (a, b) => a[key] - b[key];
  const stringCompare = (a, b) => (a[key] < b[key] ? -1 : 1);

  const compareFn = {
    age: numberCompare,
    name: stringCompare,
    //foo: customCompare
  };
  return arr.sort(compareFn[key]);
}
let arr = [
  { name: "om", age: 45 },
  { name: "guru", age: 95 },
  { name: "subh", age: 25 },
  { name: "rahul", age: 22 },
  { name: "raju", age: 35 },
];

console.log(sort(arr, "name"));
console.log(sort(arr, "age"));

相关问题