1.
Creation and Conversion Methods
These methods help create arrays or convert data types to arrays.
1. Array.from() Converts array-like or iterable objects to arrays.
let str = "Hello";
let arr = Array.from(str); // ['H', 'e', 'l', 'l', 'o']
2. Array.of() Creates an array from a set of arguments.
let arr = Array.of(1, 2, 3); // [1, 2, 3]
3. new Array() Creates an array with a specified length or values.
let arr = new Array(5); // [empty × 5]
2. Basic Methods
These methods are fundamental for array manipulation.
4. push() Adds elements to the end of the array.
let arr = [1, 2];
arr.push(3); // [1, 2, 3]
5. pop() Removes and returns the last element.
let arr = [1, 2, 3];
arr.pop(); // [1, 2]
6. unshift() Adds elements to the beginning of the array.
let arr = [1, 2];
arr.unshift(0); // [0, 1, 2]
7. shift() Removes and returns the first element.
let arr = [1, 2, 3];
arr.shift(); // [2, 3]
8. concat() Combines two or more arrays.
let arr1 = [1, 2];
let arr2 = [3, 4];
let combined = arr1.concat(arr2); // [1, 2, 3, 4]
3. Accessing and Checking Elements
9. indexOf() Finds the first occurrence of an element.
let arr = [1, 2, 3]; let index = arr.indexOf(2); // 1
10. lastIndexOf() Finds the last occurrence of an element.
let arr = [1, 2, 3, 2];
let index = arr.lastIndexOf(2); // 3
11. includes() Checks if the array contains a value.
array.lastIndexOf(searchElement, fromIndex)
let arr = [1, 2, 3];
arr.includes(2); // true
12. at() Accesses an element by its index (supports negative indices).
let arr = [1, 2, 3];
arr.at(-1); // 3
4. Iteration and Looping
13. forEach() Executes a function for each element.
[1, 2, 3].forEach(num => console.log(num)); // 1, 2, 3
14. map() Creates a new array by applying a function to each element.
let doubled = [1, 2, 3].map(num => num * 2); // [2, 4, 6]
15. filter() Filters elements based on a condition.
let filtered = [1, 2, 3, 4].filter(num => num > 2); // [3, 4]
16. reduce() Reduces the array to a single value.
let sum = [1, 2, 3].reduce((acc, num) => acc + num, 0); // 6
17. reduceRight() Similar to reduce() but starts from the right.
let sum = [1, 2, 3].reduceRight((acc, num) => acc + num, 0); // 6
18. every() Checks if all elements satisfy a condition.
[1, 2, 3].every(num => num > 0); // true
19. some() Checks if at least one element satisfies a condition.
[1, 2, 3].some(num => num > 2); // true
5. Sorting and Searching
20. sort() Sorts the array (by default lexicographically).
let arr = [3, 1, 2];
arr.sort(); // [1, 2, 3]
21. reverse() Reverses the array.
let arr = [1, 2, 3];
arr.reverse(); // [3, 2, 1]
22. find() Finds the first element that satisfies a condition.
let found = [1, 2, 3].find(num => num > 1); // 2
23. findIndex() Finds the index of the first element that satisfies a condition.
let index = [1, 2, 3].findIndex(num => num > 1); // 1
6. Splicing and Slicing
24. slice() Returns a shallow copy of a portion of the array.
let arr = [1, 2, 3];
let sliced = arr.slice(1); // [2, 3]
25. splice() Adds or removes elements from the array.
let arr = [1, 2, 3];
arr.splice(1, 1); // [2] (removed element), arr becomes [1, 3]
7. Joining and Flattening
26. join() Joins elements into a string.
let arr = [1, 2, 3];
let str = arr.join('-'); // "1-2-3"
27. flat() Flattens nested arrays.
let arr = [1, [2, [3]]];
let flattened = arr.flat(2); // [1, 2, 3]
28. flatMap() Maps and flattens the array in one step.
let arr = [1, 2];
let result = arr.flatMap(num => [num, num * 2]); // [1, 2, 2, 4]
9. Filling and Copying
29. fill() Fills an array with a static value.
let arr = [1, 2, 3];
arr.fill(0); // [0, 0, 0]
arr.fill(5, 1, 3); // [0, 5, 5]
30. copyWithin() Copies part of an array to another location in the same array.
let arr = [1, 2, 3, 4, 5]; arr.copyWithin(0, 3); // [4, 5, 3, 4, 5]
9. Advanced Searching
31. keys() Returns an iterator with the keys (indexes) of an array.
let arr = ['a', 'b', 'c'];
for (let key of arr.keys()) {
console.log(key); // 0, 1, 2 }
32. values() Returns an iterator with the values of an array.
let arr = ['a', 'b', 'c'];
for (let value of arr.values()) {
console.log(value); // 'a', 'b', 'c' }
33. entries() Returns an iterator with key-value pairs.
let arr = ['a', 'b', 'c'];
for (let [key, value] of arr.entries()) {
console.log(key, value); // 0 'a', 1 'b', 2 'c' }
10. Type Checking
34. Array.isArray() Checks if a value is an array.
Array.isArray([1, 2, 3]); // true
Array.isArray('Hello'); // false
11. Sorting Variations
35. Custom Sort Sorting with a comparator function.
let arr = [3, 1, 4, 1, 5];
arr.sort((a, b) => a - b); // [1, 1, 3, 4, 5]
12. Combining and Checking
36. some() Checks if at least one element satisfies a condition.
[1, 2, 3].some(num => num > 2); // true
37. every() Checks if all elements satisfy a condition.
[1, 2, 3].every(num => num > 0); // true
13. Array Buffers and Typed Arrays
38. Typed Arrays JavaScript supports strongly typed arrays such as Int8Array, Uint8Array, and others.
let buffer = new ArrayBuffer(16); // Create a buffer of 16 bytes
let view = new Int32Array(buffer); // Create a typed array of 32-bit integers view[0] = 42;
14. Advanced Flattening
39. reduce() for Flattening Custom implementation of flattening using reduce().
let arr = [1, [2, [3, 4]]];
let flat = arr.reduce((acc, val) => acc.concat(Array.isArray(val) ? val.flat() : val), []);
console.log(flat); // [1, 2, [3, 4]]
15. Combining and Manipulating Arrays
40. Array.prototype.concat() Combines multiple arrays into one.
let arr1 = [1, 2];
let arr2 = [3, 4];
let combined = arr1.concat(arr2, [5, 6]); // [1, 2, 3, 4, 5, 6]
41. Manual Combination Using Spread Use the spread operator to combine arrays.
let arr1 = [1, 2];
let arr2 = [3, 4];
let combined = [...arr1, ...arr2]; // [1, 2, 3, 4]
16. Transformations
42. Using reduce() for Unique Elements Find unique elements in an array.
let arr = [1, 2, 2, 3, 4, 4];
let unique = arr.reduce((acc, val) => {
if (!acc.includes(val)) acc.push(val);
return acc; }, []);
console.log(unique); // [1, 2, 3, 4]
43. Array.from() with Mapping Generate transformed arrays.
let squares = Array.from({ length: 5 }, (_, i) => i ** 2); // [0, 1, 4, 9, 16]
17. Reshaping Arrays
44. Chunking Arrays Split an array into chunks of a specific size.
let arr = [1, 2, 3, 4, 5]; let chunkSize = 2; let chunks = [];
for (let i = 0; i < arr.length; i += chunkSize) {
chunks.push(arr.slice(i, i + chunkSize));
}
console.log(chunks); // [[1, 2], [3, 4], [5]]
45. Zipping Arrays Combine two arrays index-wise.
let arr1 = [1, 2, 3];
let arr2 = ['a', 'b', 'c'];
let zipped = arr1.map((val, idx) => [val, arr2[idx]]);
console.log(zipped); // [[1, 'a'], [2, 'b'], [3, 'c']]
18. Advanced Flattening
46. Recursive Flattening with reduce() Flatten an array to any depth.
function flatten(arr) {
return arr.reduce((acc, val) =>
Array.isArray(val) ? acc.concat(flatten(val)) : acc.concat(val), []);
}
let nested = [1, [2, [3, [4]]]];
console.log(flatten(nested)); // [1, 2, 3, 4]
19. Array Statistics
47. Sum of Elements Calculate the sum of all elements.
let arr = [1, 2, 3, 4];
let sum = arr.reduce((acc, val) => acc + val, 0); // 10
48. Maximum Element Find the largest element.
let arr = [1, 2, 3, 4];
let max = Math.max(...arr); // 4
49. Minimum Element Find the smallest element.
let arr = [1, 2, 3, 4];
let min = Math.min(...arr); // 1
20. Advanced Searching
50. findLast() (ES2023) Finds the last element that matches a condition.
let arr = [1, 2, 3, 4];
let lastEven = arr.findLast(val => val % 2 === 0); // 4
51. findLastIndex() (ES2023) Finds the index of the last element that matches a condition.
let arr = [1, 2, 3, 4];
let lastEvenIndex = arr.findLastIndex(val => val % 2 === 0); // 3
21. Generating and Populating Arrays
52. Generate Sequence Create a sequence of numbers.
let sequence = Array.from({ length: 5 }, (_, i) => i + 1); // [1, 2, 3, 4, 5]
53. Randomize Array Elements Shuffle an array.
let arr = [1, 2, 3, 4, 5];
let shuffled = arr.sort(() => Math.random() - 0.5);
console.log(shuffled); // Random order
22. Set Operations with Arrays
54. Union of Two Arrays Combine two arrays and remove duplicates.
let arr1 = [1, 2, 3];
let arr2 = [3, 4, 5];
let union = [...new Set([...arr1, ...arr2])]; // [1, 2, 3, 4, 5]
55. Intersection of Two Arrays Find common elements.
let arr1 = [1, 2, 3];
let arr2 = [2, 3, 4];
let intersection = arr1.filter(val => arr2.includes(val)); // [2, 3]
56. Difference of Two Arrays Find elements in one array but not the other.
let arr1 = [1, 2, 3]; let arr2 = [2, 3, 4];
let difference = arr1.filter(val => !arr2.includes(val)); // [1]
23. Miscellaneous Techniques
57. Count Occurrences Count how often a value appears.
let arr = [1, 2, 2, 3, 3, 3];
let counts = arr.reduce((acc, val) => {
acc[val] = (acc[val] || 0) + 1;
return acc;
}, {});
console.log(counts); // {1: 1, 2: 2, 3: 3}
58. Remove Falsy Values Filter out null, undefined, false, etc.
let arr = [0, 1, false, 2, '', 3];
let cleaned = arr.filter(Boolean); // [1, 2, 3]
59. Reversing Strings in Arrays Reverse all strings in an array.
let arr = ['abc', 'def'];
let reversed = arr.map(str => str.split('').reverse().join('')); // ['cba', 'fed']
Continuing with array methods and techniques beyond 59:
24. Advanced Techniques
60. Flattening Nested Arrays with Depth Flatten an array up to a specific depth.
let arr = [1, [2, [3, [4]]]];
let flat = arr.flat(2); // [1, 2, 3, [4]]
61. Counting Unique Elements Count unique elements in an array.
let arr = [1, 2, 2, 3, 3, 3];
let counts = new Map();
arr.forEach(val => counts.set(val, (counts.get(val) || 0) + 1));
console.log(Object.fromEntries(counts)); // {1: 1, 2: 2, 3: 3}
62. Chunking Arrays Using splice() Create chunks of arrays without using slice.
let arr = [1, 2, 3, 4, 5]; let chunkSize = 2;
let chunks = [];
while (arr.length) {
chunks.push(arr.splice(0, chunkSize)); }
console.log(chunks); // [[1, 2], [3, 4], [5]]
25. Performance Tricks
63. Fast Unique Elements Using Set Remove duplicates efficiently.
let arr = [1, 2, 2, 3, 3, 3];
let unique = [...new Set(arr)]; // [1, 2, 3]
64. Efficient Sorting with Typed Arrays Sort numeric arrays faster.
let arr = new Uint32Array([5, 3, 8, 1]);
arr.sort(); // Uint32Array [1, 3, 5, 8]
65. Memory Efficient Iterations Use for...of for large datasets.
let arr = [1, 2, 3, 4];
for (let val of arr) {
console.log(val); // 1, 2, 3, 4 }
26. Custom Transformations
66. Finding Cumulative Sums Generate a cumulative sum array.
let arr = [1, 2, 3, 4];
let cumulativeSum = arr.reduce((acc, val) => {
acc.push((acc.slice(-1)[0] || 0) + val);
return acc; }, [ ]);
console.log(cumulativeSum); // [1, 3, 6, 10]
67. Split by Condition Separate an array based on a condition.
let arr = [1, 2, 3, 4];
let [evens, odds] = arr.reduce(
([even, odd], val) => (val % 2 === 0 ? [[...even, val], odd] : [even, [...odd, val]]),
[[], []]
);
console.log(evens, odds); // [2, 4] [1, 3]
27. Specialized Sorting
68. Sort Strings by Length Sort an array of strings based on their lengths.
let arr = ['apple', 'kiwi', 'banana'];
arr.sort((a, b) => a.length - b.length); // ['kiwi', 'apple', 'banana']
69. Sort Numeric Strings Sort an array of numbers stored as strings.
let arr = ['10', '2', '30'];
arr.sort((a, b) => a - b); // ['2', '10', '30']
28. Randomization Techniques
70. Select Random Elements Pick random elements from an array.
let arr = [1, 2, 3, 4, 5];
let random = arr[Math.floor(Math.random() * arr.length)];
console.log(random); // Random number
71. Shuffle Using reduce() Shuffle an array.
let arr = [1, 2, 3, 4, 5];
let shuffled = arr.reduce((acc, val, i) => {
let rand = Math.floor(Math.random() * (i + 1));
[acc[rand], acc[i]] = [acc[i], acc[rand]];
return acc;
}, [...arr]);
console.log(shuffled); // Random order
29. Array Wrapping
72. Rotate Array Rotate an array to the left or right.
let arr = [1, 2, 3, 4];
let rotatedRight = [...arr.slice(-1), ...arr.slice(0, -1)]; // [4, 1, 2, 3]
let rotatedLeft = [...arr.slice(1), ...arr.slice(0, 1)]; // [2, 3, 4, 1]
73. Wrap Values into Nested Arrays Wrap each value in an array into its own array.
let arr = [1, 2, 3];
let wrapped = arr.map(val => [val]);
console.log(wrapped); // [[1], [2], [3]]
30. Array to Object Transformations
74. Convert Key-Value Pairs to Object Transform an array of key-value pairs into an object.
let pairs = [['a', 1], ['b', 2]];
let obj = Object.fromEntries(pairs);
console.log(obj); // {a: 1, b: 2}
75. Convert Array Values into Object Keys Use array values as keys in an object.
let arr = ['a', 'b', 'c'];
let obj = arr.reduce((acc, val) => ({ ...acc, [val]: true }), {});
console.log(obj); // {a: true, b: true, c: true}
31. Array Object Techniques
76. Transform an Array into a Grouped Object Group array elements by a specific property or criteria.
let arr = [
{ category: 'fruit', name: 'Apple' },
{ category: 'fruit', name: 'Banana' },
{ category: 'vegetable', name: 'Carrot' } ];
let grouped = arr.reduce((acc, val) => {
acc[val.category] = acc[val.category] || [];
acc[val.category].push(val.name);
return acc; }, {});
console.log(grouped); // { fruit: ['Apple', 'Banana'], vegetable: ['Carrot'] }
77. Convert Array to an Indexed Object Map array values to object keys with their indices.
let arr = ['a', 'b', 'c'];
let indexed = arr.reduce((acc, val, idx) => {
acc[idx] = val;
return acc;
}, {});
console.log(indexed); // {0: 'a', 1: 'b', 2: 'c'}
32. Frequency and Patterns
78. Find the Most Frequent Element Identify the most repeated element in an array.
let arr = [1, 2, 2, 3, 3, 3, 4];
let mostFrequent = arr.reduce(
(acc, val) => {
acc.map[val] = (acc.map[val] || 0) + 1;
if (acc.map[val] > acc.maxCount) {
acc.maxCount = acc.map[val];
acc.mostFrequent = val;
}
return acc;
},
{ map: {}, maxCount: 0, mostFrequent: null }
).mostFrequent;
console.log(mostFrequent); // 3
79. Check if Array Elements are Consecutive Verify if all elements form a consecutive sequence.
let arr = [1, 2, 3, 4];
let isConsecutive = arr.every((val, idx) => idx === 0 || val === arr[idx - 1] + 1);
console.log(isConsecutive); // true
33. Advanced Array Manipulation
80. Splice with Multiple Elements Remove multiple elements and add new ones in their place.
let arr = [1, 2, 3, 4, 5];
arr.splice(1, 2, 'a', 'b'); // [1, 'a', 'b', 4, 5]
console.log(arr);
81. Create a Lookup Table Create an object for quick lookups from an array.
let arr = ['a', 'b', 'c'];
let lookup = arr.reduce((acc, val) => {
acc[val] = true;
return acc;
}, {});
console.log(lookup); // {a: true, b: true, c: true}
34. Mathematical Transformations
82. Square Every Element Calculate the square of each number in an array.
let arr = [1, 2, 3, 4];
let squares = arr.map(val => val ** 2); // [1, 4, 9, 16]
83. Sum of Squares Combine mapping and reduction for calculations.
let arr = [1, 2, 3, 4];
let sumOfSquares = arr.reduce((acc, val) => acc + val ** 2, 0); // 30
35. Comparisons and Matching
84. Find Matching Arrays Compare two arrays for exact matches.
let arr1 = [1, 2, 3]; let arr2 = [1, 2, 3];
let areEqual = arr1.length === arr2.length && arr1.every((val, idx) => val === arr2[idx]);
console.log(areEqual); // true
85. Check if Array is Subset Verify if one array is a subset of another.
let arr1 = [1, 2];
let arr2 = [1, 2, 3, 4];
let isSubset = arr1.every(val => arr2.includes(val));
console.log(isSubset); // true
36. Advanced Searching
Binary Search (Sorted Array) Perform binary search for efficiency.
function binarySearch(arr, target) {
let start = 0, end = arr.length - 1;
while (start <= end) {
let mid = Math.floor((start + end) / 2);
if (arr[mid] === target) return mid;
if (arr[mid] < target) start = mid + 1;
else end = mid - 1; }
return -1; // Not found }
let sorted = [1, 2, 3, 4, 5];
console.log(binarySearch(sorted, 3)); // 2
87. Find All Indices of a Value Locate all positions of a specific value.
let arr = [1, 2, 3, 2, 4, 2];
let indices = arr.reduce((acc, val, idx) => {
if (val === 2) acc.push(idx);
return acc; }, []);
console.log(indices); // [1, 3, 5]
37. Array Partitioning
88. Split Array by Half Divide an array into two halves.
let arr = [1, 2, 3, 4, 5];
let mid = Math.ceil(arr.length / 2);
let [firstHalf, secondHalf] = [arr.slice(0, mid), arr.slice(mid)];
console.log(firstHalf, secondHalf); // [1, 2, 3] [4, 5]
89. Split Array by Custom Predicate Split an array into two groups based on a condition.
let arr = [1, 2, 3, 4];
let [evens, odds] = arr.reduce(
([even, odd], val) => (val % 2 === 0 ? [[...even, val], odd] : [even, [...odd, val]]),
[[], []]
); console.log(evens, odds); // [2, 4], [1, 3]
38. Advanced Iteration
90. Skipping Iterations Skip iterations in a loop.
let arr = [1, 2, 3, 4, 5];
arr.forEach(val => {
if (val % 2 === 0) return; // Skips even values
console.log(val); // Prints only odd values
});
91. Custom Mapping with Index Use indices for custom mapping.
let arr = [10, 20, 30];
let newArr = arr.map((val, idx) => val + idx);
console.log(newArr); // [10, 21, 32]
39. Complex Transformations
92. Converting to Map Transform an array into a Map object for faster lookups.
let arr = [['a', 1], ['b', 2], ['c', 3]];
let map = new Map(arr);
console.log(map); // Map { 'a' => 1, 'b' => 2, 'c' => 3 }
93. Converting Map to Array Convert a Map object back into an array.
let map = new Map([['a', 1], ['b', 2]]);
let arr = Array.from(map);
console.log(arr); // [['a', 1], ['b', 2]]
40. Array Chunking
94. Divide Array into N Sized Chunks Split an array into multiple subarrays of a given size.
function chunkArray(arr, size) {
let result = [];
for (let i = 0; i < arr.length; i += size) {
result.push(arr.slice(i, i + size)); }
return result; }
let arr = [1, 2, 3, 4, 5];
console.log(chunkArray(arr, 2)); // [[1, 2], [3, 4], [5]]
41. Custom Reductions
95. Recursive Reduction Use recursion to reduce an array.
function recursiveSum(arr) {
if (arr.length === 0) return 0;
return arr[0] + recursiveSum(arr.slice(1));
}
let arr = [1, 2, 3, 4];
console.log(recursiveSum(arr)); // 10
96. Custom Reduce Function (Object Aggregation) Use reduce to aggregate complex objects.
let arr = [
{ category: 'fruit', name: 'Apple' },
{ category: 'fruit', name: 'Banana' },
{ category: 'vegetable', name: 'Carrot' }
];
let grouped = arr.reduce((acc, obj) => {
if (!acc[obj.category]) {
acc[obj.category] = [];
}
acc[obj.category].push(obj.name);
return acc;
}, {});
console.log(grouped); // { fruit: ['Apple', 'Banana'], vegetable: ['Carrot'] }
42. Combining Arrays with Logic
97. Combine Arrays While Maintaining Order Combine two arrays while keeping their original order.
let arr1 = [1, 2, 3];
let arr2 = [4, 5, 6];
let combined = [...arr1, ...arr2];
console.log(combined); // [1, 2, 3, 4, 5, 6]
98. Merge Two Arrays with Condition Merge arrays based on a condition.
let arr1 = [1, 2, 3];
let arr2 = [3, 4, 5];
let merged = [...arr1.filter(val => !arr2.includes(val)), ...arr2];
console.log(merged); // [1, 2, 3, 4, 5]
43. Flattening Arrays
99. Deep Flatten Array (Using Recursion) Flatten nested arrays of any depth.
function deepFlatten(arr) {
return arr.reduce((acc, val) => {
return Array.isArray(val) ? acc.concat(deepFlatten(val)) : acc.concat(val);
}, []);
}
let arr = [1, [2, [3, [4]]]];
console.log(deepFlatten(arr)); // [1, 2, 3, 4]
100. Flatten to Specific Depth Flatten array to a specific depth.
let arr = [1, [2, [3, [4]]]];
let flat = arr.flat(2); // [1, 2, 3, [4]]
console.log(flat);
44. Working with Nested Arrays
101. Find All Nested Elements Using Recursion Use recursion to extract all nested elements from an array.
function flattenDeep(arr) {
return arr.reduce((acc, val) => Array.isArray(val) ? acc.concat(flattenDeep(val)) : acc.concat(val), []);
}
let nestedArr = [1, [2, [3, [4, 5]]], 6];
console.log(flattenDeep(nestedArr)); // [1, 2, 3, 4, 5, 6]
102. Deep Comparison Between Arrays (Deep Equality) Compare two nested arrays deeply.
function deepEqual(arr1, arr2) {
if (arr1.length !== arr2.length) return false;
for (let i = 0; i < arr1.length; i++) {
if (Array.isArray(arr1[i]) && Array.isArray(arr2[i])) {
if (!deepEqual(arr1[i], arr2[i])) return false;
} else if (arr1[i] !== arr2[i]) {
return false;
}
}
return true;
}
let arr1 = [1, [2, 3]];
let arr2 = [1, [2, 3]];
console.log(deepEqual(arr1, arr2)); // true
45. Array Filtering and Modifying
103. Filter Unique Elements Remove duplicates and return only unique elements from an array.
let arr = [1, 2, 3, 2, 1];
let unique = [...new Set(arr)];
console.log(unique); // [1, 2, 3]
104. Filter Elements Based on Index Filter elements based on their index.
let arr = [10, 20, 30, 40, 50];
let filtered = arr.filter((val, idx) => idx % 2 === 0); // Even index elements
console.log(filtered); // [10, 30, 50]
105. Filter Elements Greater than Average Filter out all elements that are greater than the average of the array.
let arr = [10, 20, 30, 40, 50];
let avg = arr.reduce((acc, val) => acc + val, 0) / arr.length;
let greaterThanAvg = arr.filter(val => val > avg);
console.log(greaterThanAvg); // [30, 40, 50]
46. Array Set Operations
106. Set Difference Get elements present in one array but not in the other (set difference).
let arr1 = [1, 2, 3];
let arr2 = [3, 4, 5];
let diff = arr1.filter(x => !arr2.includes(x));
console.log(diff); // [1, 2]
107. Set Intersection Find common elements in two arrays (set intersection).
let arr1 = [1, 2, 3];
let arr2 = [3, 4, 5];
let intersection = arr1.filter(x => arr2.includes(x));
console.log(intersection); // [3]
108. Set Union Get the union of two arrays (all unique elements from both arrays).
let arr1 = [1, 2, 3];
let arr2 = [3, 4, 5];
let union = [...new Set([...arr1, ...arr2])];
console.log(union); // [1, 2, 3, 4, 5]
47. Slicing and Dicing Arrays
109. Extract Subarray from Start to End (non-destructive)
Use slice to extract a portion of an array without modifying the original.
let arr = [1, 2, 3, 4, 5];
let subarray = arr.slice(1, 3); // Extracts from index 1 to 2
console.log(subarray); // [2, 3]
110. Insert or Remove Elements (splice) Modify the array by inserting or removing elements.
let arr = [1, 2, 3, 4];
arr.splice(2, 1, 'a', 'b'); // Removes 1 element at index 2, adds 'a' and 'b'
console.log(arr); // [1, 2, 'a', 'b', 4]
48. Array and String Combination
111. Join Array Elements into a String Combine all elements into a single string with a separator.
let arr = ['apple', 'banana', 'cherry'];
let str = arr.join(', ');
console.log(str); // "apple, banana, cherry"
112. Split String into Array Convert a string into an array by splitting at a delimiter.
let str = "apple, banana, cherry";
let arr = str.split(', ');
console.log(arr); // ['apple', 'banana', 'cherry']
49. Array Performance Enhancements
113. Pre-allocate Array Length Avoid resizing arrays dynamically for performance improvements.
let arr = new Array(100); // Pre-allocating an array of length 100
arr.fill(0); // Fill all elements with 0
console.log(arr); // [0, 0, 0, ...]
114. Array Destructuring for Multiple VariablesEfficiently unpack array values into variables using destructuring.
let arr = [1, 2, 3];
let [a, b, c] = arr;
console.log(a, b, c); // 1 2 3
115. Check if Array is Empty Determine if an array is empty without using length explicitly.
let arr = [];
let isEmpty = !arr.length;
console.log(isEmpty); // true
50. Advanced Search and Find
116. Find First Element with Condition Find the first element in an array that meets a given condition.
let arr = [1, 2, 3, 4, 5];
let firstEven = arr.find(val => val % 2 === 0);
console.log(firstEven); // 2
117. Find the Index of a Value in Array Get the index of a particular value in the array.
let arr = [10, 20, 30, 40];
let index = arr.indexOf(30);
console.log(index); // 2
118. Find All Indices of a Value Find all indices where a specific value occurs in an array.
let arr = [1, 2, 3, 2, 4, 2];
let indices = [];
arr.forEach((val, idx) => {
if (val === 2) indices.push(idx);
});
console.log(indices); // [1, 3, 5]
51. Using Proxy with Arrays
119. Create a Proxy for an Array Use a Proxy to intercept and customize array behavior.
let arr = [1, 2, 3];
let proxy = new Proxy(arr, {
get(target, prop) {
if (prop === 'length') {
return target.length + 1; // Custom behavior for length
}
return target[prop];
}
});
console.log(proxy.length); // 4