배열의 한 속성에서 알파벳 순서로 배열의 객체 정렬


201

이와 같은 JavaScript 클래스가 있다고 가정 해 봅시다.

var DepartmentFactory = function(data) {
    this.id = data.Id;
    this.name = data.DepartmentName;
    this.active = data.Active;
}

그런 다음 해당 클래스의 인스턴스를 여러 개 만들어서 배열에 저장한다고 가정 해 봅시다.

var objArray = [];
objArray.push(DepartmentFactory({Id: 1, DepartmentName: 'Marketing', Active: true}));
objArray.push(DepartmentFactory({Id: 2, DepartmentName: 'Sales', Active: true}));
objArray.push(DepartmentFactory({Id: 3, DepartmentName: 'Development', Active: true}));
objArray.push(DepartmentFactory({Id: 4, DepartmentName: 'Accounting', Active: true}));

이제는에 의해 생성 된 객체 배열을 갖게됩니다 DepartmentFactory. array.sort()이 객체 배열 DepartmentName을 각 객체 의 속성 별로 정렬 하는 방법을 사용하려면 어떻게해야 합니까?

array.sort()방법은 문자열 배열을 정렬 할 때 잘 작동합니다.

var myarray=["Bob", "Bully", "Amy"];
myarray.sort(); //Array now becomes ["Amy", "Bob", "Bully"]

그러나 객체 목록으로 어떻게 작동합니까?


정렬 함수를 .sort ()의 첫 번째 인수로 전달할 수 있습니다.
Paul Tomblin

2
당신이 사용하고 있기 때문에 DepartmentFactory생성자로 사용하여 객체를 생성 new DepartmentFactory, 그렇지 않으면 배열의 무리와 함께 채워집니다 undefined값.
Anurag

답변:


342

다음과 같이해야합니다.

objArray.sort(function(a, b) {
    var textA = a.DepartmentName.toUpperCase();
    var textB = b.DepartmentName.toUpperCase();
    return (textA < textB) ? -1 : (textA > textB) ? 1 : 0;
});

참고 : 대 / 소문자를 변경하면 대 / 소문자를 구분하지 않습니다.


3
나는 이것을하는 방법을 결코 기억할 수 없기 때문에 당신의 대답에 50 gazillion 시대에 왔습니다. : FWIW, 내 린터 항상 "표현의 주위에 불필요한 괄호"저를 알려 return (textA < textB) ? -1 : (textA > textB) ? 1 : 0;나가 적어도 linting 일 : 기억 바랍니다 들고, 아니 거 편집 답변
마이클 Tranchida

이 Omer에 감사드립니다
Ted Fitzpatrick

이 코드에서 문제를 발견했습니다. 소문자와 대문자를 조합하여 사용하십시오. 전의. credit_card_no 및 City. 코드는 목록을 정렬하지만 'c'로 시작하는 단어는 그룹화되지 않습니다.
Kedar

156

유니 코드를 지원하려면

objArray.sort(function(a, b) {
   return a.DepartmentName.localeCompare(b.DepartmentName);
});

7
대소 문자를 구분하지 않는 버전의 경우 2 행에서 다음을 사용하십시오.return a.DepartmentName.toLowerCase().localeCompare(b.DepartmentName.toLowerCase());
Ben Barreth

3
매일 새로운 것을 배우십시오- localeCompare시원하고 첫 번째 인수에 대한 모든 브라우저 지원이 있습니다. 나쁘지 않다!
obzenner

4
@ BenBarreth는 문자열을 소문자로 지정할 이유가 없습니다. 요점은 localeCompare정렬 논리와 로케일을 관리하는 작업을 시스템으로 분류하는 것입니다. 로케일에 대해 대소 문자를 구분하지 않는 정렬을 수행하는 것이 영어로되어있는 경우에는 정상적으로 수행 "Z" > 'a' // false "Z".localeCompare('a') // 1 됩니다. 로케일의 기본값을 벗어나려면 localesand. options매개 변수 ( developer.mozilla)
Jon z

12
var DepartmentFactory = function(data) {
    this.id = data.Id;
    this.name = data.DepartmentName;
    this.active = data.Active;
}

// use `new DepartmentFactory` as given below. `new` is imporatant

var objArray = [];
objArray.push(new DepartmentFactory({Id: 1, DepartmentName: 'Marketing', Active: true}));
objArray.push(new DepartmentFactory({Id: 2, DepartmentName: 'Sales', Active: true}));
objArray.push(new DepartmentFactory({Id: 3, DepartmentName: 'Development', Active: true}));
objArray.push(new DepartmentFactory({Id: 4, DepartmentName: 'Accounting', Active: true}));

function sortOn(property){
    return function(a, b){
        if(a[property] < b[property]){
            return -1;
        }else if(a[property] > b[property]){
            return 1;
        }else{
            return 0;   
        }
    }
}

//objArray.sort(sortOn("id")); // because `this.id = data.Id;`
objArray.sort(sortOn("name")); // because `this.name = data.DepartmentName;`
console.log(objArray);

데모 : http://jsfiddle.net/diode/hdgeH/


9
// Sorts an array of objects "in place". (Meaning that the original array will be modified and nothing gets returned.)
function sortOn (arr, prop) {
    arr.sort (
        function (a, b) {
            if (a[prop] < b[prop]){
                return -1;
            } else if (a[prop] > b[prop]){
                return 1;
            } else {
                return 0;   
            }
        }
    );
}

//Usage example:

var cars = [
        {make:"AMC",        model:"Pacer",  year:1978},
        {make:"Koenigsegg", model:"CCGT",   year:2011},
        {make:"Pagani",     model:"Zonda",  year:2006},
        ];

// ------- make -------
sortOn(cars, "make");
console.log(cars);

/* OUTPUT:
AMC         : Pacer : 1978
Koenigsegg  : CCGT  : 2011
Pagani      : Zonda : 2006
*/



// ------- model -------
sortOn(cars, "model");
console.log(cars);

/* OUTPUT:
Koenigsegg  : CCGT  : 2011
AMC         : Pacer : 1978
Pagani      : Zonda : 2006
*/



// ------- year -------
sortOn(cars, "year");
console.log(cars);

/* OUTPUT:
AMC         : Pacer : 1978
Pagani      : Zonda : 2006
Koenigsegg  : CCGT  : 2011
*/

5

데모

var DepartmentFactory = function(data) {
    this.id = data.Id;
    this.name = data.DepartmentName;
    this.active = data.Active;
}

var objArray = [];
objArray.push(new DepartmentFactory({Id: 1, DepartmentName: 'Marketing', Active: true}));
objArray.push(new DepartmentFactory({Id: 2, DepartmentName: 'Sales', Active: true}));
objArray.push(new DepartmentFactory({Id: 3, DepartmentName: 'Development', Active: true}));
objArray.push(new DepartmentFactory({Id: 4, DepartmentName: 'Accounting', Active: true}));

console.log(objArray.sort(function(a, b) { return a.name > b.name}));

2
objArray.sort((a, b) => a.DepartmentName.localeCompare(b.DepartmentName))

1

이렇게 해

objArrayy.sort(function(a, b){
 var nameA=a.name.toLowerCase(), nameB=b.name.toLowerCase()
 if (nameA < nameB) //sort string ascending
  return -1
 if (nameA > nameB)
  return 1
 return 0 //default return value (no sorting)
});
console.log(objArray)

1
objArray.sort( (a, b) => a.id.localeCompare(b.id, 'en', {'sensitivity': 'base'}));

알파벳순으로 정렬하며 대소 문자를 구분하지 않습니다. 또한 매우 깨끗하고 읽기 쉽습니다. : D


허용 된 솔루션보다 훨씬 더 우아합니다!
kano

0

다음은 속성을 통해 객체 배열을 정렬하는 데 사용할 수있는 간단한 함수입니다. 속성이 문자열 또는 정수 유형인지 여부는 중요하지 않습니다.

    var cars = [
        {make:"AMC",        model:"Pacer",  year:1978},
        {make:"Koenigsegg", model:"CCGT",   year:2011},
        {make:"Pagani",     model:"Zonda",  year:2006},
    ];

    function sortObjectsByProp(objectsArr, prop, ascending = true) {
        let objectsHaveProp = objectsArr.every(object => object.hasOwnProperty(prop));
        if(objectsHaveProp)    {
            let newObjectsArr = objectsArr.slice();
            newObjectsArr.sort((a, b) => {
                if(isNaN(Number(a[prop])))  {
                    let textA = a[prop].toUpperCase(),
                        textB = b[prop].toUpperCase();
                    if(ascending)   {
                        return textA < textB ? -1 : textA > textB ? 1 : 0;
                    } else {
                        return textB < textA ? -1 : textB > textA ? 1 : 0;
                    }
                } else {
                    return ascending ? a[prop] - b[prop] : b[prop] - a[prop];
                }
            });
            return newObjectsArr;
        }
        return objectsArr;
    }

    let sortedByMake = sortObjectsByProp(cars, "make"); // returns ascending order by its make;
    let sortedByYear = sortObjectsByProp(cars, "year", false); // returns descending order by its year,since we put false as a third argument;
    console.log(sortedByMake);
    console.log(sortedByYear);


-1

두 개의 매개 변수를 허용하고 비교 한 다음 숫자를 반환하는 함수를 전달해야합니다. 따라서 ID를 기준으로 정렬하려는 경우 ...

objArray.sort(function(a,b) {
    return a.id-b.id;
});
// objArray is now sorted by Id

5
그는 ID가 아닌 DepartmentName을 기준으로 정렬에 대해 물었습니다.
Paul Tomblin

나는 이것을 시도했지만 이것은 문자열 열에서 작동하지 않는 것 같습니다 ... 날짜 열에서 작동했습니다. 어떤 일을하는 것은 @ 오메르-bokhari의 솔루션이었다
tsando

-2

이것에 대해 조금 시도하고 가능한 한 적은 루프를 만들려고하면이 솔루션으로 끝났습니다.

코드 펜 데모

const items = [
      {
        name: 'One'
      },
      {
        name: 'Maria is here'
      },
      {
        name: 'Another'
      },
      {
        name: 'Z with a z'
      },
      {
        name: '1 number'
      },
      {
        name: 'Two not a number'
      },
      {
        name: 'Third'
      },
      {
        name: 'Giant'
      }
    ];

    const sorted = items.sort((a, b) => {
      return a[name] > b[name];
    });

    let sortedAlphabetically = {};

    for(var item in sorted) {
      const firstLetter = sorted[item].name[0];
      if(sortedAlphabetically[firstLetter]) {
        sortedAlphabetically[firstLetter].push(sorted[item]);
      } else {
        sortedAlphabetically[firstLetter] = [sorted[item]]; 
      }
    }

    console.log('sorted', sortedAlphabetically);

-3

간단한 대답 :

objArray.sort(function(obj1, obj2) {
   return obj1.DepartmentName > obj2.DepartmentName;
});

ES6 방법 :

objArray.sort((obj1, obj2) => {return obj1.DepartmentName > obj2.DepartmentName};

소문자 / 대문자 등을 만들어야하는 경우 해당 변수를 비교하는 것보다 그 결과를 변수에 저장하십시오. 예:

objArray.sort((obj1, obj2) => {
   var firstObj = obj1.toLowerCase();
   var secondObj = obj2.toLowerCase();
   return firstObj.DepartmentName > secondObj.DepartmentName;
});
당사 사이트를 사용함과 동시에 당사의 쿠키 정책개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.