다음과 같은 객체 배열이 있다고 가정합니다. -
const arr = [
{
'name' : 'd',
'index' : 3
},
{
'name' : 'c',
'index' : 2
},
{
'name' : 'a',
'index' : 0
},
{
'name' : 'b',
'index' : 1
}
]; 이러한 배열을 취하는 JavaScript 함수를 작성해야 합니다.
함수는 개체의 인덱스 속성에 따라 이 배열을 오름차순으로 정렬해야 합니다.
그런 다음 함수는 정렬된 배열을 각 문자열이 개체의 해당 이름 속성 값인 문자열 배열에 매핑해야 합니다.
따라서 위의 배열에서 최종 출력은 다음과 같아야 합니다. -
const output = ["a", "b", "c", "d"];
예시
이에 대한 코드는 -
const arr = [
{
'name' : 'd',
'index' : 3
},
{
'name' : 'c',
'index' : 2
},
{
'name' : 'a',
'index' : 0
},
{
'name' : 'b',
'index' : 1
}
];
const sortAndMap = (arr = []) => {
const copy = arr.slice();
const sorter = (a, b) => {
return a['index'] - b['index'];
};
copy.sort(sorter);
const res = copy.map(({name, index}) => {
return name;
});
return res;
};
console.log(sortAndMap(arr)); 출력
콘솔의 출력은 -
[ 'a', 'b', 'c', 'd' ]