DEV Community

Whoissosick
Whoissosick

Posted on • Edited on

Working with arrays [JS]

Function methods

.pop()

The pop() method removes the last element from an array and returns that element.

let fruits = ["apple", "banana", "orange"];
let lastFruit = fruits.pop();
console.log(fruits); // ["apple", "banana"]
console.log(lastFruit); // "orange"
Enter fullscreen mode Exit fullscreen mode

.unshift()

Adds one or more elements to the beginning of an array and returns its new length. It works similarly to push().

let numbers = [2, 3];
let newLength = numbers.unshift(1);
console.log(numbers); // [1, 2, 3]
console.log(newLength); // 3
Enter fullscreen mode Exit fullscreen mode

.shift()

Removes the first element from an array and returns that element. It's similar to pop().

let colors = ["red", "green", "blue"];
let firstColor = colors.shift();
console.log(colors); // ["green", "blue"]
console.log(firstColor); // "red"
Enter fullscreen mode Exit fullscreen mode

One-Dimensional and Two-Dimensional Arrays

A one-dimensional array, often called an array, is like a single row of boxes.

Two-dimensional array is essentially an array of arrays.

let chessboard = [
    ["R", "N", "B", "Q", "K", "B", "N", "R"],
    ["P", "P", "P", "P", "P", "P", "P", "P"],
    [" ", " ", " ", " ", " ", " ", " ", " "],
    [" ", " ", " ", " ", " ", " ", " ", " "],
    [" ", " ", " ", " ", " ", " ", " ", " "],
    [" ", " ", " ", " ", " ", " ", " ", " "],
    ["p", "p", "p", "p", "p", "p", "p", "p"],
    ["r", "n", "b", "q", "k", "b", "n", "r"]
];

console.log(chessboard[0][3]); // Outputs: "Q"
Enter fullscreen mode Exit fullscreen mode

Array Destructuring

let fruits = ["apple", "banana", "orange"];

let [first, second, third] = fruits;

console.log(first);  // "apple"
console.log(second); // "banana"
console.log(third);  // "orange"
Enter fullscreen mode Exit fullscreen mode

Array destructuring also allows you to skip elements you're not interested in by using commas. For instance:

let colors = ["red", "green", "blue", "yellow"];
let [firstColor, , thirdColor] = colors;

console.log(firstColor); // Output: "red"
console.log(thirdColor); // Output: "blue"
Enter fullscreen mode Exit fullscreen mode

Another powerful feature of array destructuring is the ability to use default values.

let numbers = [1, 2];
let [a, b, c = 3] = numbers;

console.log(a); // 1
console.log(b); // 2
console.log(c); // 3
Enter fullscreen mode Exit fullscreen mode

Now, let's discuss the rest syntax, denoted by three dots (...). It allows you to capture the remaining elements of an array that haven’t been destructured into a new array.

The rest syntax must be the last element in the destructuring pattern.

let fruits = ["apple", "banana", "orange", "mango", "kiwi"];
let [first, second, ...rest] = fruits;

console.log(first);  // "apple"
console.log(second); // "banana"
console.log(rest);   // ["orange", "mango", "kiwi"]
Enter fullscreen mode Exit fullscreen mode

How Can You Use String and Array Methods to Reverse a String?

Steps

  • Splitting the string into an array of characters.
  • Reversing the array.
  • Joining the characters back into a string.

The first step in reversing a string is to convert it into an array of individual characters. We can do this using the split() method.
*An empty string (""), which splits the string into individual characters.
*A single space (" "), which splits the string wherever spaces occur.
*A dash ("-"), which splits the string at each dash.

let str = "hello";
let charArray = str.split("");
console.log(charArray); // ["h", "e", "l", "l", "o"]
Enter fullscreen mode Exit fullscreen mode

The reverse() method is an array method that reverses an array in place. This means it modifies the original array rather than creating a new one.

let charArray = ["h", "e", "l", "l", "o"];
charArray.reverse();
console.log(charArray); // ["o", "l", "l", "e", "h"]
Enter fullscreen mode Exit fullscreen mode

We can accomplish this using the join() method. The join() method creates and returns a new string by concatenating all of the elements in an array, separated by a specified separator string.

let reversedArray = ["o", "l", "l", "e", "h"];
let reversedString = reversedArray.join("");
console.log(reversedString); // "olleh"
Enter fullscreen mode Exit fullscreen mode

Remember that strings in JavaScript are immutable, which means you can't directly reverse a string by modifying it. That's why we need to convert it to an array, reverse the array, and then convert it back to a string. This combination of string and array methods provides a powerful and flexible way to manipulate strings in JavaScript.

let str = "coding";
let reversed = str.split("").reverse().join("");
console.log(reversed);
Enter fullscreen mode Exit fullscreen mode

How Do You Get the Index for an Element in an Array Using the indexOf Method?

let fruits = ["apple", "banana", "orange", "banana"];
let index = fruits.indexOf("banana");
console.log(index); // 1
Enter fullscreen mode Exit fullscreen mode

If the element you're searching for is not found in the array, indexOf() returns -1.

If you want to start looking for an item after a specific index number, then you can pass a second argument like in this example:

let colors = ["red", "green", "blue", "yellow", "green"];
let index = colors.indexOf("green", 3);
console.log(index); // 4
Enter fullscreen mode Exit fullscreen mode

In this example, the search does not start from the start of an array, rather it starts from the index number 3 which is yellow and gets the output of 4.

In order to find the proper object in an array use findIndex() method

const userIndex = users.findIndex(user => user.name === 'Dave');
Enter fullscreen mode Exit fullscreen mode

How Do You Add and Remove Elements from the Middle of an Array?

**.splice()

The return value for the splice() method will be an array of the items removed from the array. If nothing was removed, then an empty array will be returned. This method will mutate the original array, modifying it in place rather than creating a new array.

array.splice(startIndex, itemsToRemove, item1, item2)
Enter fullscreen mode Exit fullscreen mode

startIndex specifies the index at which to begin modifying the array, while itemsToRemove is an optional parameter indicating how many elements to remove. If itemsToRemove is omitted, splice() will remove all elements from startIndex to the end of the array. The subsequent parameters (item1, item2, and so on) are the elements to be added to the array, beginning at the start index.

let fruits = ["apple", "banana", "orange", "mango", "kiwi"];
let removed = fruits.splice(2, 2);

console.log(fruits);  // ["apple", "banana", "kiwi"]
console.log(removed); // ["orange", "mango"]
Enter fullscreen mode Exit fullscreen mode

In this example, splice(2, 2) starts at index 2 and removes 2 elements.

Now, let's look at how to add elements to the middle of an array:

let colors = ["red", "green", "blue"];
colors.splice(1, 0, "yellow", "purple");

console.log(colors); // ["red", "yellow", "purple", "green", "blue"]
Enter fullscreen mode Exit fullscreen mode

Here, splice(1, 0, "yellow", "purple") starts at index 1, removes 0 elements, and inserts yellow and purple. The second parameter (0) means no elements are removed before insertion. You can also use splice() to simultaneously remove and add elements:

let numbers = [1, 2, 3, 4, 5];
numbers.splice(1, 2, 6, 7, 8);

console.log(numbers); // [1, 6, 7, 8, 4, 5]
Enter fullscreen mode Exit fullscreen mode

In this case, splice(1, 2, 6, 7, 8) starts at index 1, removes 2 elements (2 and 3), and inserts 6, 7, and 8.

One common use case for splice() is to remove a single element from an array when you know its index:

let fruits = ["apple", "banana", "orange", "mango"];
let indexToRemove = fruits.indexOf("orange");
if (indexToRemove !== -1) {
    fruits.splice(indexToRemove, 1);
}

console.log(fruits); // ["apple", "banana", "mango"]
Enter fullscreen mode Exit fullscreen mode

You can also use splice() to clear an array by removing all elements:

let array = [1, 2, 3, 4, 5];
array.splice(0);

console.log(array); // []
Enter fullscreen mode Exit fullscreen mode

How Can You Check if an Array Contains a Certain Value?

In JavaScript, the includes() method is a simple and efficient way to check if an array contains a specific value. This method returns a boolean value: true if the array contains the specified element, and false otherwise.

let fruits = ["apple", "banana", "orange", "mango"];
console.log(fruits.includes("banana")); // true
console.log(fruits.includes("grape"));  // false
Enter fullscreen mode Exit fullscreen mode

The includes() method can also accept an optional second parameter that specifies the position in the array to start the search. This is useful if you want to check for an element's presence in a specific part of the array. Here's how you can use this feature:

let numbers = [10, 20, 30, 40, 50, 30, 60];
console.log(numbers.includes(30, 3)); // true
console.log(numbers.includes(30, 4)); // true
Enter fullscreen mode Exit fullscreen mode

It's worth noting that includes() uses the strict equality comparison (===), which means it can distinguish between different types. For example:

let mixedArray = [1, "2", 3, "4", 5];
console.log(mixedArray.includes(2));  // false
console.log(mixedArray.includes("2")); // true
Enter fullscreen mode Exit fullscreen mode

In this case, the number 2 and the string "2" are considered different data types. So, the first console.log will return false, while the second console.log will return true.

What Is a Shallow Copy of an Array, and What Are Some Ways to Create These Copies?

If the array only contains primitive values like numbers or strings, the new array is completely separate. But if the array contains other arrays inside it, both the original and the copy have references to the same inner arrays. This means that if you change something inside a shared inner array, you will see that change in both arrays.

There are several methods for creating shallow copies of arrays, and we'll explore some of the most common ones: concat(), slice(), and the spread operator.

Let's start with the concat() method. This method creates a new array by merging two or more arrays. When used with a single array, it effectively creates a shallow copy. Here's an example:

const originalArray = [1, 2, 3];
const copyArray = [].concat(originalArray);

console.log(copyArray); // [1, 2, 3]
console.log(copyArray === originalArray); // false
Enter fullscreen mode Exit fullscreen mode

In this example, we are using the concat() method to concatenate an empty array to the originalArray. This will create a new array that is a shallow copy of originalArray.

The copyArray contains the same elements as originalArray, but it is a different array object, which is why the strict equality check (===) returns false.

Another method to create a shallow copy is the slice() method. When called without arguments, slice() returns a shallow copy of the entire array. Here's how it works:

const originalArray = [1, 2, 3];
const copyArray = originalArray.slice();

console.log(copyArray); // [1, 2, 3]
console.log(copyArray === originalArray); // false
Enter fullscreen mode Exit fullscreen mode

In this case, originalArray.slice() creates a new array that is a shallow copy of originalArray. Again, the copyArray contains the same elements but is a different array object.

The spread operator (...), introduced in ES6, provides another concise way to create shallow copies of arrays. Here's an example:

const originalArray = [1, 2, 3];
const copyArray = [...originalArray];

console.log(copyArray); // [1, 2, 3]
console.log(copyArray === originalArray); // false
Enter fullscreen mode Exit fullscreen mode

The spread operator (...) spreads the elements of originalArray into a new array, effectively creating a shallow copy. It's important to note that all these methods create new array objects, which means you can modify the copy without affecting the original array.

Top comments (0)