对象按照属性进行排序

{

A:[5,0,0],

B: [0,2,3],

C:[0,3,2],

}

按照第一列排序,按第二列,最后一列。

可以按照以下步骤进行排序:

  1. 将对象转换为数组,每个属性对应一个数组元素,其中元素的第一个值为属性名,第二个值为属性值的数组。
  2. 使用Array.sort()方法对数组进行排序,排序时传入一个自定义的比较函数,用于比较两个数组元素的大小。
  3. 在比较函数中,首先比较两个数组元素的第一个值,如果第一个值相同,则比较第二个值,以此类推。
  4. 排序完成后,将数组转换回对象形式。

以下是实现代码:

const obj = {
    
    
  A: [5, 0, 0],
  B: [0, 2, 3],
  C: [0, 3, 2]
};

const arr = Object.entries(obj); // 将对象转换为数组

arr.sort((a, b) => {
    
    
  for (let i = 0; i < a[1].length; i++) {
    
    
    if (a[1][i] !== b[1][i]) {
    
    
      return a[1][i] - b[1][i];
    }
  }
  return 0;
}); // 对数组进行排序

const sortedObj = Object.fromEntries(arr); // 将数组转换回对象形式

console.log(sortedObj); // 输出{ B: [ 0, 2, 3 ], C: [ 0, 3, 2 ], A: [ 5, 0, 0 ] }

在上面的代码中,我们首先使用Object.entries()方法将对象obj转换为数组arr,然后使用Array.sort()方法对数组进行排序,排序时传入一个比较函数,该函数会比较两个数组元素的大小。在比较函数中,我们使用一个循环来比较两个数组元素的每一个值,如果发现不同的值,就返回它们的差值,如果所有值都相同,则返回0。最后,使用Object.fromEntries()方法将排序后的数组arr转换回对象形式,得到排序后的对象sortedObj

[

{’A’:5},

{‘B’:2,‘C’:3},

{‘B’:3,‘C’:2},

]

对数组的对象进行排序,

let newArr = []
 arr.map(item=>{
    
    
    newArr.push(Object.fromEntries(Object.entries(item).sort((a,b)=>b[1]-a[1])))
 })
function sortByProperty(obj, prop) {
    
    
    // 将对象转化为键值对数组
    const entries = Object.entries(obj);
    const sortedEntries = entries.sort((a, b) => b[1][prop] - a[1][prop]);
    // 将数组转化为对象
    return Object.fromEntries(sortedEntries);
  }
  
  // 示例用法
  const obj = {
    
    
    a: {
    
     name: 'Alice', age: 25 },
    b: {
    
     name: 'Bob', age: 30 },
    c: {
    
     name: 'Charlie', age: 20 }
  };
  const result = sortByProperty(obj, 'age');
  console.log(result); // { c: { name: 'Charlie', age: 20 }, a: { name: 'Alice', age: 25 }, b: { name: 'Bob', age: 30 } }

猜你喜欢

转载自blog.csdn.net/qq_43720551/article/details/131237686
今日推荐