Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> JavaScript

การจัดเรียงตัวเลขภายในตัวเลข (Sort Digits Within Numbers) ใน JavaScript

ภาพรวม

บทความนี้สาธิตวิธีจัดเรียงหลักตัวเลขภายในแต่ละตัวเลขในอาร์เรย์ ให้เรียงจากน้อยไปมาก

ตัวอย่าง

Input:  [543, 65, 343, 75, 567, 878, 87]
Output: [345, 56, 334, 57, 567, 788, 78]
// 543 -> 345, 65 -> 56, 343 -> 334, 75 -> 57, 567 -> 567, 878 -> 788, 87 -> 78

การนำไปใช้

const ascendNumber = (num) => {
  return String(num)
    .split('')
    .map(Number)
    .sort((a, b) => a - b)
    .join('');
};

const sortDigits = (arr) => arr.map(ascendNumber);

console.log(sortDigits([543, 65, 343, 75, 567, 878, 87]));

ผลลัพธ์

['345', '56', '334', '57', '567', '788', '78']

คืนค่าเป็น Number แทน String

const sortDigitsAsNumber = (arr) => 
  arr.map(num => Number(
    String(num).split('').sort((a, b) => a - b).join('')
  ));

console.log(sortDigitsAsNumber([543, 65, 343, 75, 567, 878, 87]));
// [345, 56, 334, 57, 567, 788, 78]

จัดการตัวเลขติดลบและทศนิยม

const sortDigitsAdvanced = (num) => {
  const str = String(num);
  const isNegative = str[0] === '-';
  const hasDecimal = str.includes('.');
  
  let [intPart, decPart] = str.replace('-', '').split('.');
  
  const sortPart = (s) => [...s].sort((a, b) => a - b).join('');
  
  let result = sortPart(intPart);
  if (hasDecimal) result += '.' + sortPart(decPart);
  if (isNegative) result = '-' + result;
  
  return hasDecimal ? Number(result) : parseInt(result);
};

console.log(sortDigitsAdvanced(-543.21)); // -123.45

การประยุกต์ใช้

  • Digit Manipulation Puzzles
  • Number Theory: Digit Properties
  • Game Development: Number Puzzle Games
  • Data Obfuscation

ข้อควรระวัง

  • Leading Zeros: 100 -> 001 -> 1 (หายไป) ต้องตัดสินใจว่าเก็บเป็น String หรือ Number
  • Negative Numbers: ต้องจัดการเครื่องหมายแยก
  • Floating Point: จุดทศนิยมคงเดิมหรือจัดเรียงรวม?
  • Large Numbers: ใช้ String ทั้งหมด (BigInt)