#How to Manipulate JavaScript Arrays – CloudSavvy IT

“#How to Manipulate JavaScript Arrays – CloudSavvy IT”

Illustration showing the JavaScript logo

JavaScript arrays are data structures which let you store multiple values under a single variable name. Arrays are a type of object. They come with several utility methods you can use to manipulate their data.

Arrays in JavaScript have very relaxed restrictions around what you can place within them. They have neither a fixed length nor a specific type. They behave more like a list of values than the classical arrays of strongly typed languages.

Declaring an Array

JavaScript arrays use squared brackets. You can initialize them empty, or add a series of default values. Values are separated by commas. You may use any valid JavaScript value, such as a string, an integer, an object, or another array.

let emptyArray = [];
let filledArray = ["hello", 123, {foo: "bar"}, ["x", "y"]];

Accessing Array Values

You retrieve a value from an array by specifying the index that you want to access. Array indexes are numbered from 0. Use the square bracket syntax to define the array index to retrieve.

let myArray = ["foo", "bar", "example"];
// logs "bar"

Array indexes are always integers in JavaScript. You can’t use strings as indexes—use an object instead if you need to do that.

You can change the value of an array index by setting it directly:

myArray shown above would now contain the values foo, test, example.

Adding Items to Arrays

You add new items to arrays using the push() method:

["car", "truck"].push("bus");
// car, truck, bus

This adds the item to the end of the array. If you’d like the new element to be inserted at the start of the array, use the unshift() method instead.

["car", "truck"].unshift("bus");
// bus, car, truck

Sometimes you might need to insert an element mid-way through an array. You can use the splice() method to add an item at a specific index:

["car", "truck"].splice(1, 0, "bus");
// car, bus, truck

The first argument to splice() is the index to make the insertion at. Next comes the number of items to delete from the start of the array. When you’re adding a new item, this should be 0 so that the existing elements are retained. The final argument is the item to add.

Removing Items from Arrays

To remove an array item, use the pop() method. It will “pop” the last item out of the array:

["car", "truck", "bus"].pop();
// car, truck

To remove the first array element, use the shift() method instead:

["car", "truck", "bus"].shift();
// truck, bus

If you want to remove a specific item, you’ll need to use the splice() method again. You’ll need to know the index you want to remove first. If you’re working from one of the array’s values, first call indexOf() to get its index. You can then pass this to splice(), setting the second argument to 1 to delete one item at the given index.

const arr = ["car", "truck", "bus"];
arr.splice(arr.indexOf("truck"), 1);
// car, bus

Iterating over Arrays

There are several ways in which you can iterate over an array. The traditional approach is to use a for loop:

const arr = ["car", "truck", "bus"];
for (let i = 0; i < arr.length; i++) {
    console.log(`Vehicle at position ${i} is ${arr[i]}`);

A shorter alternative is to use the array’s forEach() method. This must be given a function. The function is called once for each item in the array. It receives each item’s value and index as its parameters.

["car", "truck", "bus"].forEach((vehicle, i) => {
    console.log(`Vehicle at position ${i} is ${vehicle}`);

forEach() is often easier to work with than a for loop. You should take care when returning values, though. Returning from the function passed to forEach() won’t cancel the loop:

const arr = ["car", "truck", "bus"];
// logs "car"
for (let i = 0; i < arr.length; i++) {
    if (arr[i] === "truck") return;
// logs "car", "truck", "bus"
arr.forEach((vehicle, i) => {
    if (vehicle === "truck") return;

With forEach(), the return statement returns from the anonymous function. The loop is created by the outer scope, so it continues to call the function anew for the remaining items in the array.

Mapping Arrays

map() is one of JavaScript’s most powerful array methods. It accepts a function that will be called for each item in the array. A new array containing the results of each function call is then returned.

const arr = [2, 4, 8, 16];
const mapped = => (v * v));
// mapped contains 4, 16, 64, 256

Your callback function actually receives three arguments—the value at the current position, the index of the current position, and the array that map() is being called upon.

[1, 2, 3].map((value, index, arr) => (value * value));

Mapping is useful when you need to iterate over an array, access each value, and then derive some new value from that iteration. The technique is also useful when working with UI frameworks such as React, where you can map over data to transform it into a DOM node:

const MyComponent = users => ( => (

Consider using map() whenever you need to perform some action on every element in an array, even if you’re not interested in the return value of your callback.

Filtering Arrays

Another common task is filtering an array to exclude certain elements. You might be inclined to create a new empty array and use a for loop to test elements in your original. A simpler approach would be to use JavaScript’s built-in filter() method.

Like map(), filter() takes a callback function that gets invoked on each iteration. The current value, index and array, are passed to the callback as parameters. The callback must return either true or false to indicate whether the current value should be included in the new filtered array.

const filtered = [1, 2, 3].filter(v => (v % 2 === 0));
// filtered is [2]

Using filter() makes filtering quick and concise. You don’t need to build a for loop and set up the new array yourself. The method always returns a new array and will not mutate the original.

Utility Methods

Here are a few other methods you may find useful.

  • Joining two arrays: Use the concat() method to join two arrays together. It will return a new array, with its argument appended to the array it was called on. ["a, "b", "c"].concat(["x", "y", "z"]) returns ["a", "b", "c", "x", "y", "z"].
  • Converting an array to a string: Use the join() method to combine an array’s values into a single string. You can specify the separator as the first parameter to the function. ["a", "b", "c"].join(" - ") will return a - b - c.
  • Getting value indexes: If you know that a value exists in an array, you can get its numerical index with indexOf(). If the value exists multiple times in the array, the index of the first occurrence is returned. You can get the index of the last occurrence using lastIndexOf().
  • Determining whether a value exists in an array: The includes() method accepts a value and lets you check whether it exists in an array. It returns a boolean indicating whether the value was found. ["a", "b", "c"].includes("a") would return true.
  • Creating an empty array with a predetermined length: You can use the Array constructor to initialize an empty array with a given length. const myArr = new Array(10) would create an array with 10 indexes (0-9), each with undefined as its value.
  • Testing whether all elements in an array match a condition: Sometimes you might want to check whether every element in an array meets a condition. The every() method lets you do this. It accepts a callback that works similarly to the filter() method. The method will only return true if every invocation of the callback returns true. If you want to know whether only some of the array elements match, use the some() method instead.


JavaScript arrays are a versatile data structure with useful built-in methods. Compared with other languages, working with arrays in JavaScript is simple and concise. You can quickly iterate, map, and filter values using inline arrow functions that keep your code clean and readable.

If you liked the article, do not forget to share it with your friends. Follow us on Google News too, click on the star and choose us from your favorites.

For forums sites go to Forum.BuradaBiliyorum.Com

If you want to read more like this article, you can visit our Technology category.


Related Articles

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top button