10 JavaScript Array Snippets for Everyday Development
Arrays are everywhere in JavaScript. Whether you're processing API responses, filtering UI lists, or transforming data, these ready-to-use snippets cover the most common array tasks. Each example is practical, concise, and uses modern ES6+ syntax.
1. Filter Out Falsy Values
Remove null, undefined, 0, "", and false from an array in one line:
const values = [1, null, "hello", 0, undefined, true, ""];
const clean = values.filter(Boolean);
// [1, "hello", true]
2. Remove Duplicates
Use a Set to deduplicate an array of primitives instantly:
const nums = [1, 2, 2, 3, 4, 4, 5];
const unique = [...new Set(nums)];
// [1, 2, 3, 4, 5]
3. Find an Object in an Array
Use find() to get the first matching object:
const users = [
{ id: 1, name: "Alice" },
{ id: 2, name: "Bob" },
];
const user = users.find(u => u.id === 2);
// { id: 2, name: "Bob" }
4. Group Items by a Property
Group an array of objects into a dictionary by a shared key:
const items = [
{ type: "fruit", name: "apple" },
{ type: "veggie", name: "carrot" },
{ type: "fruit", name: "banana" },
];
const grouped = items.reduce((acc, item) => {
(acc[item.type] = acc[item.type] || []).push(item);
return acc;
}, {});
// { fruit: [...], veggie: [...] }
5. Flatten a Nested Array
const nested = [1, [2, 3], [4, [5, 6]]];
const flat = nested.flat(Infinity);
// [1, 2, 3, 4, 5, 6]
6. Sum All Numbers
const prices = [9.99, 4.50, 14.00, 2.75];
const total = prices.reduce((sum, price) => sum + price, 0);
// 31.24
7. Sort Objects by a Property
const products = [
{ name: "Widget", price: 25 },
{ name: "Gadget", price: 10 },
{ name: "Doohickey", price: 40 },
];
const sorted = products.sort((a, b) => a.price - b.price);
// Sorted cheapest to most expensive
8. Chunk an Array into Smaller Arrays
Split a large array into fixed-size chunks — useful for pagination:
function chunk(arr, size) {
return Array.from({ length: Math.ceil(arr.length / size) }, (_, i) =>
arr.slice(i * size, i * size + size)
);
}
chunk([1, 2, 3, 4, 5], 2);
// [[1, 2], [3, 4], [5]]
9. Check if All/Some Items Match a Condition
const ages = [22, 30, 17, 25];
const allAdults = ages.every(age => age >= 18); // false
const someAdults = ages.some(age => age >= 18); // true
10. Map and Filter in One Pass
Use flatMap() to transform and filter simultaneously, avoiding an extra iteration:
const numbers = [1, 2, 3, 4, 5];
const doubledEvens = numbers.flatMap(n => (n % 2 === 0 ? [n * 2] : []));
// [4, 8]
Wrapping Up
These snippets cover the vast majority of array tasks you'll encounter in real projects. Bookmark this page and reach for the right method — your future self (and your teammates) will thank you for writing clean, expressive array code instead of verbose loops.