Javascript codes ที่ใช้บ่อย ๆ

วันที่: 27 มี.ค. 2565 23:55 น.

Javascript codes ที่ใช้บ่อย ๆ

การเรียงลำดับ Array (array sort)

const no = [4, 2, 1, 3];
no.sort();
// [1, 2, 3, 4]

 

การเรียงลำดับแบบสุ่มของ Array

const shuffleArray = (arr) => arr.sort(() => 0.5 - Math.random());
console.log(shuffleArray([1, 2, 3, 4, 5]));
// [1, 5, 4, 2, 3]

 

การเรียงลำดับกรณีมี object key value

const myArray = [{name:"alex"},{name:"clex"},{name:"blex"}];
myArray.sort((a,b)=> (a.name > b.name ? 1 : -1)); // ASC
// myArray.sort((a,b)=> (a.name < b.name ? 1 : -1)); // DESC
console.log(myArray);

 

การเช็คว่ามีค่าที่ต้องการใน Array หรือไม่

var myArray = [2,5,6,7,9,6];
console.log(myArray.includes(2)) // is true
console.log(myArray.includes(14)) // is false

 

การตัดค่าซ้ำของ Array (remove duplicates)

function onlyUnique(value, index, self) {
  return self.indexOf(value) === index;
}

// usage example:
var a = ['a', 1, 'a', 2, '1'];
var unique = a.filter(onlyUnique);

console.log(unique); // ['a', 1, 2, '1']

 

การหาจำนวนวันระหว่างวันที่

const dayDif = (date1, date2) => Math.ceil(Math.abs(date1.getTime() - date2.getTime()) / 86400000)
dayDif(new Date("2021-10-21"), new Date("2022-10-22"))
// Result: 366

เรื่องอื่น ๆ ที่เกี่ยวข้อง