ViewertViewert

JavaScript Array Methods

By Sunrostern · · 7 min read

Filter

The .filter() method in JavaScript is used to create a new array containing all elements of the original array that meet a specified condition. The condition is defined by a provided callback function. This method does not change the original array.

Syntax

array.filter(callback(element[, index[, array]])[, thisArg])

Parameters

  1. callback: A function that is executed on each element of the array. It takes three arguments:

    • element: The current element being processed in the array.

    • index (optional): The index of the current element being processed in the array.

    • array (optional): The array filter was called upon.

  2. thisArg (optional): An object to use as this when executing the callback.

Return Value

  • A new array with all elements that pass the test implemented by the provided function.

Example

Here’s an example of using .filter() to get all elements in an array that are greater than a certain value:

const array = [5, 12, 8, 130, 44];

const filteredArray = array.filter(element => element > 10);

console.log(filteredArray); // Output: [12, 130, 44]

In this example, the filter method creates a new array containing only the elements from the original array that are greater than 10.

Example with All Parameters

const array = [5, 12, 8, 130, 44];

const filteredArray = array.filter((element, index, array) => {
  console.log('Element:', element);
  console.log('Index:', index);
  console.log('Array:', array);
  return element > 10;
});

console.log(filteredArray); // Output: [12, 130, 44]

In this example:

  • element: The current element being processed.

  • index: The index of the current element.

  • array: The array filter was called on.

Example Using thisArg

If you need to use a specific context (the value of this) within the callback, you can provide thisArg:

const array = [5, 12, 8, 130, 44];

const context = { threshold: 10 };

const filteredArray = array.filter(function(element) {
  return element > this.threshold; // `this` refers to `context`
}, context);

console.log(filteredArray); // Output: [12, 130, 44]

In this case, the callback function uses this.threshold to access the threshold property from the context object.

Summary

  • The .filter() method creates a new array with elements that pass the test defined by the provided function.

  • It does not modify the original array.

  • It takes a callback function that can accept up to three parameters: element, index, and array.

  • An optional thisArg parameter can be used to set the value of this inside the callback function.

Find

The .find() method in JavaScript is used to search for a specific element in an array that meets a certain condition defined by a provided function. It returns the first element in the array that satisfies the provided testing function. If no elements satisfy the testing function, undefined is returned.

Here is the syntax:

array.find(callback(element[, index[, array]])[, thisArg])
  • callback: A function that is executed on each element of the array until it returns true, indicating that the element satisfies the condition. It takes three arguments:

    • element: The current element being processed in the array.

    • index (optional): The index of the current element being processed in the array.

    • array (optional): The array find was called upon.

  • thisArg (optional): An object to use as this when executing the callback.

Example

const array = [5, 12, 8, 130, 44];

const found = array.find(element => element > 10);

console.log(found); // Output: 12

In this example, .find() is used to search for the first element greater than 10 in the array. The method finds 12, which is the first element that satisfies the condition, and returns it.

Sort

The .sort() method in JavaScript is used to sort the elements of an array in place and returns the sorted array. The default sort order is ascending, built upon converting the elements into strings and comparing their sequences of UTF-16 code unit values.

Syntax

array.sort([compareFunction])

Parameters

  • compareFunction (optional): A function that defines the sort order. If omitted, the array elements are converted to strings and sorted according to each character's Unicode code point value.

Default Sorting Behavior

Without a compare function, the .sort() method converts elements to strings and sorts them lexicographically (in dictionary order):

const array = [40, 1, 5, 200];
array.sort();
console.log(array); // Output: [1, 200, 40, 5]

Custom Sorting with Compare Function

The compare function takes two arguments, a and b, and returns:

  • A negative value if a should come before b.

  • Zero if a and b are considered equal.

  • A positive value if a should come after b.

Example: Numeric Sort in Ascending Order

const array = [40, 1, 5, 200];

array.sort((a, b) => a - b);
console.log(array); // Output: [1, 5, 40, 200]

Example: Numeric Sort in Descending Order

const array = [40, 1, 5, 200];

array.sort((a, b) => b - a);
console.log(array); // Output: [200, 40, 5, 1]

Sorting Strings Alphabetically

const fruits = ['banana', 'apple', 'cherry'];

fruits.sort();
console.log(fruits); // Output: ['apple', 'banana', 'cherry']

Sorting Objects by a Property

const items = [
  { name: 'Edward', value: 21 },
  { name: 'Sharpe', value: 37 },
  { name: 'And', value: 45 },
  { name: 'The', value: -12 },
  { name: 'Magnetic', value: 13 },
  { name: 'Zeros', value: 37 }
];

items.sort((a, b) => a.value - b.value);
console.log(items);
// Output: 
// [
//   { name: 'The', value: -12 },
//   { name: 'Magnetic', value: 13 },
//   { name: 'Edward', value: 21 },
//   { name: 'Sharpe', value: 37 },
//   { name: 'Zeros', value: 37 },
//   { name: 'And', value: 45 }
// ]

Caveats

  1. In-place Sorting: .sort() sorts the array in place, meaning it changes the original array and returns it. It does not create a new array.

  2. Non-stable Sort: JavaScript's .sort() is not guaranteed to be stable, meaning the relative order of equal elements might not be preserved.

  3. String Conversion: By default, elements are converted to strings and sorted lexicographically. This can lead to unexpected results when sorting numbers.

Summary

  • The .sort() method sorts the elements of an array in place and returns the sorted array.

  • By default, it sorts elements as strings in lexicographical order.

  • A custom compare function can be provided to define different sorting orders.

  • It is important to remember that .sort() modifies the original array.

Splice

The .splice() method in JavaScript is used to change the contents of an array by removing, replacing, or adding elements at specific indices. It directly modifies the original array and returns an array containing the deleted elements.

Syntax

array.splice(start, deleteCount, item1, item2, ...);

Parameters

  1. start: The index at which to start changing the array. If greater than the length of the array, actual starting index will be set to the length of the array. If negative, it will begin that many elements from the end of the array (i.e., array.length + start).

  2. deleteCount (optional): An integer indicating the number of elements to remove from the array. If deleteCount is 0 or negative, no elements are removed. If omitted, all elements from start to the end of the array are removed.

  3. item1, item2, ... (optional): The elements to add to the array, beginning at the start index. If not specified, splice() only removes elements from the array.

Return Value

  • An array containing the deleted elements. If no elements are removed, an empty array is returned.

Examples

Removing Elements

const array = ['Jan', 'Feb', 'Mar', 'Apr', 'May'];

const removed = array.splice(2, 1); // Removes 1 element at index 2
console.log(array); // Output: ['Jan', 'Feb', 'Apr', 'May']
console.log(removed); // Output: ['Mar']

Adding Elements

const array = ['Jan', 'Feb', 'Mar', 'Apr', 'May'];

array.splice(2, 0, 'New Month'); // Adds 'New Month' at index 2
console.log(array); // Output: ['Jan', 'Feb', 'New Month', 'Mar', 'Apr', 'May']

Replacing Elements

const array = ['Jan', 'Feb', 'Mar', 'Apr', 'May'];

const removed = array.splice(2, 1, 'New Month'); // Replaces 1 element at index 2
console.log(array); // Output: ['Jan', 'Feb', 'New Month', 'Apr', 'May']
console.log(removed); // Output: ['Mar']

Using Negative Start Index

const array = ['Jan', 'Feb', 'Mar', 'Apr', 'May'];

const removed = array.splice(-2, 1); // Removes 1 element from the second-to-last position
console.log(array); // Output: ['Jan', 'Feb', 'Mar', 'May']
console.log(removed); // Output: ['Apr']

Summary

  • .splice() modifies the original array and returns an array of deleted elements.

  • You can use it to remove, add, or replace elements in an array.

  • The method directly changes the array on which it is called.