const objectArray = [{
a: "hello",
b: "world"
},
{
a: "javascript",
b: "basic"
},
{
a: "start",
b: "study"
}]
이런 Array가 있고 우리는 이런 Array를 내가 원하는 대로 sort하고 싶다.
그런데 내부 값은 string 값이라 sort 할 수 없다.
그렇다면 어떻게 해야할까?
const objectArray = [{
index: 3,
a: "hello",
b: "world"
},
{
index: 1,
a: "javascript",
b: "basic"
},
{
index: 2,
a: "start",
b: "study"
}]
이렇게 정보를 추가해준다. 그리고나서
const sortedArray = objectArray.sort((element)=>{ if(element.index > element.index){
return 1
}
if(element.index < element.index){
return -1
}
return 0
})
이렇게 해주면 정렬이 된다. 각종 데이터를 다룰 때 유용하다.