본문 바로가기

html | javascript

html javascript - array sort, reverse

function init() {
   const arr0 = ['car','bus','aircraft','spacecraft','car1','motorcycle','car']
   const arr1 = [
     {name: 'car', type: 'land', cost: 100},
     {name: 'bus', type: 'land', cost: 50},
     {name: 'aircraft', type: 'sky', cost: 200},
     {name: 'motorcycle', type: 'land', cost: 80},
     {name: 'spacecraft', type: 'space', cost: 1000}
   ]
   const arr2 = [5,3,21,6,50,100,1,10,12,20,2]

   const sort0 = arr0.concat([]).sort()
   const sort1 = arr2.concat([]).sort()
   console.log(sort0) // [ "aircraft", "bus", "car", "car", "car1", "motorcycle", "spacecraft" ]
   console.log(sort1) // [ 1, 10, 100, 12, 2, 20, 21, 3, 5, 50, 6 ]

   const sort2 = arr2.concat([]).sort((a,b) => a - b)
   const sort3 = arr2.concat([]).sort((a,b) => b - a)
   console.log(sort2) // [ 1, 2, 3, 5, 6, 10, 12, 20, 21, 50, 100 ]
   console.log(sort3) // [ 100, 50, 21, 20, 12, 10, 6, 5, 3, 2, 1 ]

   const reverse0 = sort0.reverse()
   const reverse1 = sort1.reverse()
   const reverse2 = sort2.reverse()
   const reverse3 = sort3.reverse()
   console.log(reverse0) // [ "spacecraft", "motorcycle", "car1", "car", "car", "bus", "aircraft" ]
   console.log(reverse1) // [ 6, 50, 5, 3, 21, 20, 2, 12, 100, 10, 1 ]
   console.log(reverse2) // [ 100, 50, 21, 20, 12, 10, 6, 5, 3, 2, 1 ]
   console.log(reverse3) // [ 1, 2, 3, 5, 6, 10, 12, 20, 21, 50, 100 ]

   const sort4 = arr1.concat([]).sort((a,b) => {
     if (a.cost < b.cost) return -1
     if (a.cost > b.cost) return 1
     return 0
   })
   console.log(sort4) // bus, motorcycle, car, aircraft, spacecraft

   const reverse4 = sort4.reverse()
   console.log(reverse4) // spacecraft, aircraft, car, motorcycle, bus
 }

 

arr0.concat([]) 은 array copy 

array.sort() 는 array를 직접 수정