Skip to content

Archive

JavaScript

52 articles
JavaScript Updated 07 Sep 2025 1 min read

Sort JavaScript Object Arrays by a Property Value

JavaScript comparator functions make it straightforward to sort arrays of objects by a numeric property. const data = [ { name: 'Edward', order: 21 }, { name: 'Sharpe', order: 37 }, { name: 'And', order: 45 }, { name: 'The', order: -12 }, { name: 'Magnetic', order: 13 }, { name: 'Zeros', order: 37 }, ]; Descending Order const sorted = data.toSorted((a, b) => b.order - a.order); This places the largest order value first.

JavaScript Updated 02 Sep 2025 1 min read

Find Text and Extract Context from a JavaScript String

Sometimes a search result is more useful when it includes nearby text instead of returning only an index. A small helper can find a substring and return a configurable amount of context around it. function findTextContext(text, query, context = 100) { const index = text.indexOf(query); if (index === -1) return null; const start = Math.max(0, index - context); const end = Math.min(text.length, index + query.length + context); return text.slice(start, end); } Example const text = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed do eiusmod tempor.'; const result = findTextContext(text, 'consectetur', 20); console.log(result); The helper finds the first occurrence and includes up to 20 characters before and after it.

JavaScript Updated 07 Sep 2025 2 min read

Filter JavaScript Arrays Quickly and Clearly

Array.prototype.filter() creates a new array containing only the elements that satisfy a predicate. It does not modify the original array. Filter by a Condition const values = [1, 2, 3, 4, 5, 6]; const even = values.filter((value) => value % 2 === 0); console.log(even); // [2, 4, 6] Filter Objects by a Property const users = [ { name: 'Alice', age: 25 }, { name: 'Bob', age: 30 }, { name: 'Charlie', age: 25 }, ]; const age25 = users.filter((user) => user.age === 25); Remove Duplicates For primitive values, a Set is usually clearer than using filter() with indexOf:

JavaScript Updated 02 Sep 2025 2 min read

Manage Asynchronous Operations with Promises and Async/Await in JavaScript

Promises represent values that may become available later. async and await provide syntax for working with promises using control flow that resembles synchronous code. Create a Promise function callFirstName() { return new Promise((resolve) => { setTimeout(() => resolve('John'), 1000); }); } A promise can be fulfilled with resolve or rejected with reject.