logo

Sorting Objects in Ascending Order, Comparing Objects for Equality

  • Sorting an Object’s Keys in Ascending Order
function sortObjectByKeys(obj) {
    return Object.keys(obj)
        .sort() // Sort keys in ascending order
        .reduce((sortedObj, key) => {
            sortedObj[key] = obj[key];
            return sortedObj;
        }, {});
}
  • Sorting an Object’s Keys in Descending Order
function sortObjectByKeysDescending(obj) {
  return Object.keys(obj)
    .sort((a, b) => b.localeCompare(a)) // Sort keys in descending order
    .reduce((sortedObj, key) => {
      sortedObj[key] = obj[key]; // Insert into new object in the order of sorted keys
      return sortedObj;
    }, {});
}
  • Comparing Two Objects for Equality of Keys and Values
function areObjectsEqual(obj1, obj2) {
    if (Object.keys(obj1).length !== Object.keys(obj2).length) return false;
    for (let key in obj1) {
        if (obj1[key] !== obj2[key]) return false;
    }
    return true;
}
One minute to read

Prime number check

function isPrime(num) {
  if (num === 2) {
    return true
  } else if (num % 2 === 0) {
    return false
  }
  let sqrt = parseInt(Math.sqrt(num))
  for (let i = 3; i <= sqrt; i = i + 2) {
    if (num % i === 0) {
      return false
    }
  }
  return true
}
One minute to read

Finding Divisors

Divisors: An integer that can divide another integer without a remainder.

  1. Finding divisors by dividing all numbers

Condition: Add the number if the remainder is 0 when divided.

Skip if the condition is not met.

Range of condition: The divisor can be at most the number itself, so set the loop to iterate up to the number.

    let num = 8; // 약수를 찾기 위한 정수 설정
    let result = []
    let index = 1;
    
    while (index <= num) {
      if (num % index === 0) result.push(index)
      index++
    }
    console.log(result) // [ 1, 2, 4, 8 ]
  1. Checking only up to half of the given number

Divisors, except for the number itself, cannot be larger than num / 2, so check only up to half.

2 minutes to read