Program Tip

각 요소의 길이를 기준으로 배열을 정렬하는 방법은 무엇입니까?

programtip 2020. 10. 13. 19:06
반응형

각 요소의 길이를 기준으로 배열을 정렬하는 방법은 무엇입니까?


다음과 같은 배열이 있습니다.

arr = []
arr[0] = "ab"
arr[1] = "abcdefgh"
arr[2] = "abcd"

정렬 후 출력 배열은 다음과 같아야합니다.

arr[0] = "abcdefgh"
arr[1] = "abcd"
arr[2] = "ab"  

내 말은, 각 요소의 길이의 내림차순으로 원합니다.


Array.sort방법을 사용 하여 배열을 정렬 할 수 있습니다 . 문자열의 길이를 정렬 기준으로 고려하는 정렬 함수는 다음과 같이 사용할 수 있습니다.

arr.sort(function(a, b){
  // ASC  -> a.length - b.length
  // DESC -> b.length - a.length
  return b.length - a.length;
});

참고 : ["a", "b", "c"]문자열 길이로 정렬 하면 ["a", "b", "c"]. 사양 에 따르면 :

정렬이 반드시 안정적인 것은 아닙니다 (즉, 동일하게 비교되는 요소가 반드시 원래 순서대로 유지되는 것은 아닙니다).

길이별로 정렬 한 다음 사전 순서로 정렬하는 것이 목표 인 경우 추가 기준을 지정해야합니다.

["c", "a", "b"].sort(function(a, b) {
  return a.length - b.length || // sort by length, if equal then
         a.localeCompare(b);    // sort by dictionary order
});

요청한대로 javascript가있는 문자열의 길이에 따라 정렬은 다음과 같습니다.

[버블 정렬에 의한 문제 해결] [1]

[1] : http://jsfiddle.net/sssonline2/vcme3/2/enter code here


Array.sort 메서드를 사용 하여이 배열을 정렬 할 수 있습니다 .

ES5 솔루션

var array = ["ab", "abcdefgh", "abcd"];

array.sort(function(a, b){return b.length - a.length});

console.log(JSON.stringify(array, null, '\t'));

대한 오름차순으로 정렬 순서 :a.length - b.length

대한 내림차순으로 정렬 순서를 :b.length - a.length

ES6 솔루션

주의 : 모든 브라우저가 ES6 코드를 이해할 수있는 것은 아닙니다!

ES6에서는 화살표 함수 표현식을 사용할 수 있습니다 .

let array = ["ab", "abcdefgh", "abcd"];

array.sort((a, b) => b.length - a.length);

console.log(JSON.stringify(array, null, '\t'));


Salman의 대답에 따라 캡슐화하는 작은 함수를 작성했습니다.

function sortArrayByLength(arr, ascYN) {
        arr.sort(function (a, b) {           // sort array by length of text
            if (ascYN) return a.length - b.length;              // ASC -> a - b
            else return b.length - a.length;                    // DESC -> b - a
        });
    }

그런 다음

sortArrayByLength( myArray, true );

안타깝게도이 페이지에 설명 된대로 함수를 Array 프로토 타입에 추가 할 수 있거나 추가해서는 안됩니다 .

Also, it modified the array passed as a parameter and doesn't return anything. This would force the duplication of the array and wouldn't be great for large arrays. If someone has a better idea, please do comment!


I adapted @shareef's answer to make it concise. I use,

.sort(function(arg1, arg2) { return arg1.length - arg2.length })


<script>
         arr = []
         arr[0] = "ab"
         arr[1] = "abcdefgh"
         arr[2] = "sdfds"
         arr.sort(function(a,b){
            return a.length<b.length
         })
         document.write(arr)

</script>

The anonymous function that you pass to sort tells it how to sort the given array.hope this helps.I know this is confusing but you can tell the sort function how to sort the elements of the array by passing it a function as a parameter telling it what to do

참고URL : https://stackoverflow.com/questions/10630766/how-to-sort-an-array-based-on-the-length-of-each-element

반응형