Code Highlights logo

Learn

Arrays

More Array Methods

  1. The .splice() Method: Removing and Replacing Elements The .splice() method is a powerful tool that allows you to remove or replace elements within an array. By specifying the start index and the number of elements to remove or replace, you can easily modify the contents of your array.
    1const fruits = ['apple', 'banana', 'orange', 'kiwi'];
    2fruits.splice(1, 2, 'pear', 'grape');
    3console.log(fruits); // Output: ['apple', 'pear', 'grape', 'kiwi']
  2. The .slice() Method: Extracting a Portion of an Array The .slice() method allows you to create a new array containing a portion of an existing array. By specifying the start and end indexes, you can extract a subarray from your original array without modifying it.
    1const fruits = ['apple', 'banana', 'orange', 'kiwi'];
    2const citrusFruits = fruits.slice(1, 3);
    3console.log(citrusFruits); // Output: ['banana', 'orange']
  3. The .indexOf() Method: Finding the Index of an Element The .indexOf() method allows you to find the index of a specified element within an array. It returns the first occurrence of the element found, or -1 if the element is not present in the array.
    1const fruits = ['apple', 'banana', 'orange', 'kiwi'];
    2const orangeIndex = fruits.indexOf('orange');
    3console.log(orangeIndex); // Output: 2
  4. The .includes() Method: Checking for Element Existence The .includes() method allows you to quickly check if an array includes a specific element. It returns a boolean value indicating whether the element is found or not.
    1const fruits = ['apple', 'banana', 'orange', 'kiwi'];
    2const hasBanana = fruits.includes('banana');
    3console.log(hasBanana); // Output: true

Instructions

1.

Use the concat() method to merge two arrays. Create a new array called moreNumbers by merging numbers array with the following array [6, 7, 8].

2.

Use the indexOf() method to find the index of the number 4 in the numbers array. Assign the result to a variable called indexOfFour.

Sign up to start coding

Already have an account?

Sign In

Course content