Built-in array methods and functional patterns commonly tested in interviews.
JavaScript arrays have a rich set of built-in methods. Interviews frequently test map, filter, reduce, and less common methods like flat, flatMap, and findIndex.
const nums = [1, 2, 3, 4, 5];// map — transform each element, returns new array of same lengthnums.map(n => n * 2); // [2, 4, 6, 8, 10]// filter — keep elements that pass the test, returns new arraynums.filter(n => n % 2 === 0); // [2, 4]// reduce — accumulate into a single valuenums.reduce((acc, n) => acc + n, 0); // 15// reduceRight — same but right-to-left
const arr = [3, 1, 4, 1, 5, 9];// sort mutates the original arrayarr.sort((a, b) => a - b); // [1, 1, 3, 4, 5, 9] ascendingarr.sort((a, b) => b - a); // [9, 5, 4, 3, 1, 1] descending// String sort["banana", "apple", "cherry"].sort((a, b) => a.localeCompare(b));
array.sort() without a comparator converts elements to strings and sorts lexicographically. [10, 9, 2].sort() gives [10, 2, 9]. Always provide a comparator for numbers.
These modify the original array — know when to avoid them:
Copy
arr.push(item); // add to end, returns new lengtharr.pop(); // remove from end, returns removed itemarr.unshift(item); // add to startarr.shift(); // remove from startarr.splice(1, 2); // remove 2 elements starting at index 1arr.reverse(); // reverses in place