首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >按两个条件对对象数组进行排序

问按两个条件对对象数组进行排序
EN

Stack Overflow用户
提问于 2022-12-02 12:30:16
回答 3查看 69关注 0票数 1

我需要按两个条件对对象数组进行排序

  1. 按值
  2. 排序,如果名称相同,则按值顺序

显示它们相邻。

示例示例:https://codesandbox.io/s/relaxed-dhawan-sfryng?file=/src/index.js

EN

回答 3

Stack Overflow用户

发布于 2022-12-02 12:33:58

若要按多个条件对对象数组进行排序,可以使用Array.prototype.sort()方法并提供自定义排序函数。自定义排序函数应该以两个对象作为参数,并返回一个值,指示如何在排序数组中排序。

下面是一个示例,说明如何实现自定义排序函数,该函数按值对数组进行排序,如果值相同,则按名称排序:

代码语言:javascript
复制
function sortByValueAndName(a, b) {
  // If the values are different, sort by value
  if (a.value !== b.value) {
    return a.value - b.value;
  }

  // If the values are the same, sort by name
  if (a.name !== b.name) {
    return a.name < b.name ? -1 : 1;
  }

  // If both the values and the names are the same, the objects are equal
  return 0;
}

// Example array of objects
const objects = [
  { name: "John", value: 10 },
  { name: "Jane", value: 10 },
  { name: "Alice", value: 5 },
];

// Sort the array using the custom sorting function
objects.sort(sortByValueAndName);

// The sorted array will be:
// [
//   { name: "Alice", value: 5 },
//   { name: "John", value: 10 },
//   { name: "Jane", value: 10 },
// ]

注意,sort()方法修改了数组,因此不需要将sort()方法的结果赋值给一个新变量。排序后的数组将在您所调用的sort()上相同的变量中可用。

票数 1
EN

Stack Overflow用户

发布于 2022-12-02 13:17:19

我为它提供了一个解决方案,它有点复杂,您可以阅读我添加的评论

​

代码语言:javascript
复制
const array = [
  {
    name: "John",
    value: 5
  },
  {
    name: "David",
    value: 6
  },
  {
    name: "John",
    value: 2
  },
  {
    name: "Michael",
    value: 4
  }
];

const customSort = (data) => {
  
  // create a new array to make elements have same name together
  let newArray = data.reduce((a,v) => {
    let obj = a.find(e => e.name === v.name)
    if(obj){
     obj.datas.push(v) 
    }else{
     a.push({'name':v.name,'datas':[v]})
    }
    return a
  },[])
  
  // sort data in the new array by value
  newArray.forEach(e => {
   e.datas.sort((a,b) => a.value - b.value) 
  })

  // create a value object with boolean value to avoid add duplicate element
  let values = data.reduce((a,v) => {
    a[v.value] = false
    return a
  },{})
  let keys = Object.keys(values)

  let result = []
  for(k of keys){
  
    // if the value has iterated,then skip it
    if(values[k]){
     continue
    }
    // find data by value
    let arr = newArray.filter(e1 => e1.datas.some(e2 => e2.value == k)).flatMap(e => e.datas)
    result.push(...arr)
    
    // mark the value already added
    arr.forEach(e => {
      values[e.value] = true 
    })
  }
 return result
}


console.log(customSort(array))

​

票数 0
EN

Stack Overflow用户

发布于 2022-12-02 14:21:31

希望它有帮助:

​

代码语言:javascript
复制
const arr = [
  {
    name: "John",
    value: 5
  },
  {
    name: "David",
    value: 6
  },
  {
    name: "John",
    value: 2
  },
  {
    name: "Michael",
    value: 4
  }
];

const groupByItems = [];

// Get index of the item based on name in groupByItems array
const getIndex = (name) => {
  let index = -1;
  groupByItems.forEach((groupByItem, _index) => {
    if(groupByItem.name === name) {
      index = _index;
    }
  });
  return index;
}

// Group items by their name
const groupByName = () => {
  arr.forEach((item) => {
    const name = item.name;
    const value = item.value;
    let index = getIndex(name);
    //Means that the [name] has not added before, so we should add it
    if(index === -1) {
      groupByItems.push({
        name: name,
        // Hold all values of the [name]
        values: [],
        // Hold minValue to sort groupByItems by that
        minValue: Infinity
      });
      index = groupByItems.length - 1;
    }
    // Add current value to the list of values
    groupByItems[index].values.push(value);
    // Update minValue
    if(groupByItems[index].minValue > value) {
      groupByItems[index].minValue = value;
    }
  });
}

groupByName();

//Sort by minValue and then return final objects
const result = groupByItems.sort((a, b) => a.minValue - b.minValue).flatMap((item) => (
  item.values.sort((firstValue, secondValue) => firstValue - secondValue).map((value) => {
    return {
      name: item.name,
      value: value
    }
  })
));

console.log(result);

​

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/74655807

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档