The problem
Need common array operations that aren't built into JavaScript
The solution
const arrayUtils = {
// Remove duplicates from array
unique(arr) {
return [...new Set(arr)];
},
// Flatten nested array
flatten(arr) {
return arr.reduce((flat, next) => {
return flat.concat(Array.isArray(next) ? this.flatten(next) : next);
}, []);
},
// Group array by key
groupBy(arr, key) {
return arr.reduce((groups, item) => {
const groupKey = item[key];
if (!groups[groupKey]) {
groups[groupKey] = [];
}
groups[groupKey].push(item);
return groups;
}, {});
},
// Chunk array into smaller arrays
chunk(arr, size) {
const chunks = [];
for (let i = 0; i < arr.length; i += size) {
chunks.push(arr.slice(i, i + size));
}
return chunks;
},
// Find object by property value
findByProperty(arr, prop, value) {
return arr.find(item => item[prop] === value);
},
// Sort array of objects by property
sortByProperty(arr, prop, ascending = true) {
return arr.sort((a, b) => {
const aVal = a[prop];
const bVal = b[prop];
const comparison = aVal < bVal ? -1 : aVal > bVal ? 1 : 0;
return ascending ? comparison : -comparison;
});
},
// Calculate average
average(arr) {
if (arr.length === 0) return 0;
return arr.reduce((sum, val) => sum + val, 0) / arr.length;
},
// Shuffle array (Fisher-Yates algorithm)
shuffle(arr) {
const shuffled = [...arr];
for (let i = shuffled.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[shuffled[i], shuffled[j]] = [shuffled[j], shuffled[i]];
}
return shuffled;
}
};Put it to work
const numbers = [1, 2, 2, 3, 4, 4, 5];
const users = [
{ id: 1, name: 'Alice', age: 25 },
{ id: 2, name: 'Bob', age: 30 },
{ id: 3, name: 'Alice', age: 28 }
];
console.log('Unique:', arrayUtils.unique(numbers)); // [1,2,3,4,5]
console.log('Chunked:', arrayUtils.chunk(numbers, 3)); // [[1,2,2],[3,4,4],[5]]
console.log('Grouped by name:', arrayUtils.groupBy(users, 'name'));
console.log('Find by ID:', arrayUtils.findByProperty(users, 'id', 2));
console.log('Sorted by age:', arrayUtils.sortByProperty(users, 'age'));
console.log('Average age:', arrayUtils.average(users.map(u => u.age)));
console.log('Shuffled:', arrayUtils.shuffle(numbers));