@FahadM to JavaScriptEnglish • 5 days ago

How do you sort an array of JavaScript objects by numeric or string property values?

message-square
0
1
How do you sort an array of JavaScript objects by numeric or string property values?
@FahadM to JavaScriptEnglish • 5 days ago

To sort an array of JavaScript objects by a numeric or string property without mutating the original array, first make a shallow copy ([...items]) and use a type-aware comparator: compare finite numbers via (aNum - bNum) * direction (handling NaN or Infinity explicitly) and compare strings via String(aStr).localeCompare(String(bStr), locales, options) * direction (with numeric: true when sorting natural/alphanumeric strings). Always validate inputs, guard against null/missing keys or unsafe property names, and return a deterministic tie-breaker on equal values.


1. Sorting Objects by a Numeric Property Safely (Number.isFinite + [...items].sort(...))

Validate that items is an array and propName is a safe non-empty string key, clone the array before sorting, and handle non-numeric or missing values without letting NaN corrupt the comparator:

// Normalize a numeric property value into a finite number or NaN
function toFiniteNumber(rawValue) {
  if (typeof rawValue === "number") {
    return Number.isFinite(rawValue) ? rawValue : Number.NaN;
  }

  if (typeof rawValue === "string" && rawValue.trim() !== "") {
    const parsed = Number(rawValue);
    return Number.isFinite(parsed) ? parsed : Number.NaN;
  }

  return Number.NaN;
}

// Sort an array of objects by a numeric property without mutating the source array
function sortObjectsByNumber(items, propName, { order = "asc", invalidLast = true } = {}) {
  if (!Array.isArray(items)) {
    throw new TypeError("Expected items to be an Array.");
  }

  if (typeof propName !== "string" || propName.trim() === "") {
    throw new TypeError("Expected propName to be a non-empty string.");
  }

  const key = propName.trim();
  if (key === "__proto__" || key === "constructor" || key === "prototype") {
    throw new RangeError(`Refusing unsafe property key "${key}".`);
  }

  const direction = order === "desc" ? -1 : 1;

  return [...items]
    .map((item, index) => ({
      item,
      index,
      num:
        item && typeof item === "object" && Object.prototype.hasOwnProperty.call(item, key)
          ? toFiniteNumber(item[key])
          : Number.NaN
    }))
    .sort((left, right) => {
      const leftValid = !Number.isNaN(left.num);
      const rightValid = !Number.isNaN(right.num);

      if (!leftValid && !rightValid) {
        return left.index - right.index;
      }
      if (!leftValid) {
        return invalidLast ? 1 : -1;
      }
      if (!rightValid) {
        return invalidLast ? -1 : 1;
      }
      if (left.num === right.num) {
        return left.index - right.index;
      }

      return (left.num - right.num) * direction;
    })
    .map((entry) => entry.item);
}

// Example usage:
const products = Object.freeze([
  { id: "p1", name: "Keyboard", price: 75 },
  { id: "p2", name: "Mouse", price: 25 },
  { id: "p3", name: "Monitor", price: 220 }
]);

const cheapestFirst = sortObjectsByNumber(products, "price", { order: "asc" });
console.log("Cheapest first:", cheapestFirst.map((p) => p.name)); // ["Mouse", "Keyboard", "Monitor"]
console.log("Original order preserved:", products.map((p) => p.name)); // ["Keyboard", "Mouse", "Monitor"]
  • Non-mutating & Object.freeze() safe: Clones before .sort() and preserves original array order.
  • Explicit NaN & tie handling: Keeps invalid/missing numbers deterministic and breaks ties by original index.

2. Sorting Objects by a String Property with localeCompare()

When sorting by a text property (such as names, titles, or codes), use localeCompare() rather than raw < / > operators so case folding, accented characters, and optional natural number ordering (numeric: true) behave consistently:

// Sort an array of objects by a string property using localeCompare without mutating input
function sortObjectsByString(
  items,
  propName,
  { order = "asc", locales = undefined, sensitivity = "base", numeric = false } = {}
) {
  if (!Array.isArray(items)) {
    throw new TypeError("Expected items to be an Array.");
  }

  if (typeof propName !== "string" || propName.trim() === "") {
    throw new TypeError("Expected propName to be a non-empty string.");
  }

  const key = propName.trim();
  if (key === "__proto__" || key === "constructor" || key === "prototype") {
    throw new RangeError(`Refusing unsafe property key "${key}".`);
  }

  const direction = order === "desc" ? -1 : 1;

  return [...items]
    .map((item, index) => {
      const hasOwn = item && typeof item === "object" && Object.prototype.hasOwnProperty.call(item, key);
      const rawVal = hasOwn ? item[key] : null;
      const strVal =
        typeof rawVal === "string"
          ? rawVal
          : rawVal === null || rawVal === undefined
            ? ""
            : String(rawVal);

      return { item, index, strVal, isMissing: rawVal === null || rawVal === undefined };
    })
    .sort((left, right) => {
      if (left.isMissing && right.isMissing) {
        return left.index - right.index;
      }
      if (left.isMissing) {
        return 1;
      }
      if (right.isMissing) {
        return -1;
      }

      const cmp = left.strVal.localeCompare(right.strVal, locales, {
        sensitivity,
        numeric
      });

      if (cmp !== 0) {
        return cmp * direction;
      }

      return left.index - right.index;
    })
    .map((entry) => entry.item);
}

// Example usage:
const chapters = [
  { id: 1, code: "item-10" },
  { id: 2, code: "item-2" },
  { id: 3, code: "item-1" }
];

const naturalSorted = sortObjectsByString(chapters, "code", { numeric: true });
console.log("Natural order:", naturalSorted.map((c) => c.code)); // ["item-1", "item-2", "item-10"]
  • Natural alphanumeric ordering: { numeric: true } sorts "item-2" before "item-10" instead of lexicographically.
  • Locale & case control: sensitivity: "base" groups base characters predictably across cases and accents.

3. Common Traps to Avoid

Sorting arrays of objects by numeric or string properties often runs into a few pitfalls:

  • Sorting numbers with default .sort() or localeCompare(): Without a numeric comparator, numbers coerce to strings so 100 sorts before 20 ("100" < "20").
  • Using raw a.name > b.name for strings: Raw ASCII/UTF-16 comparisons put uppercase letters ("Zebra") ahead of lowercase letters ("apple") and misorder accented characters.
  • Mutating shared arrays in place with arr.sort(...): Always copy first ([...arr].sort(...)) when working with shared references, props, or frozen arrays.

TL;DR: Copy first ([...arr].sort(...)) to avoid mutation, use (aNum - bNum) * direction (with finite-number and NaN guards) for numeric properties, and use aStr.localeCompare(bStr, locales, { numeric }) * direction for string properties.