Categories
JavaScript

More JavaScript Array Tips

Spread the love

Replacing and mapping entries

JavaScript, like any other programming language, has many handy tricks that let us write our programs more easily. In this article, we will look at how to do different things that involve arrays, like replacing specific values from an array and mapping array entries from one value to another.

Replacing Specific Value From an Array

There are a few ways to replace specific values from an array. We can use the indexOf method to get the first occurrence of an array and then use the index to assign a new value to the entry in that array index. For example, we can use the indexOf method like the following code:

const arr = ['apple', 'orange', 'grape', 'banana'];
const index = arr.indexOf('orange');
arr[index] = 'chicken';
console.log(arr);

The indexOf is called on arr and takes in any object that we want to get the first index of in the array. It works best with primitive values since it doesn’t do deep checks for objects, so it only works by checking the references for objects. In the third line, we reassigned the value of the index that is assigned by the indexOf method, which should be 1. Then, we assigned it the new value 'chicken'. Then, we should get the following output from the console.log statement on the last line:

["apple", "chicken", "grape", "banana"]

Note that we can use const to declare arr since we aren’t assigning any new value to any property of arr so it will work without errors.

We can also use the splice method to replace one or more values of an array. This method lets us removing, replace an existing element or adding new elements in place. The argument of the splice method is the starting index start of which to start changing the array. It can be positive or negative. If it’s negative, then it’ll start changing the array from the end and move towards the start of the array. The end index is -1, the second is -2 and so on. The second argument of the splice method is the deleteCount, which is an optional argument that lets us specify how many items to delete starting from the start parameter in the first element. Subsequent arguments are the items that we want to insert into an array. This can go on for as long as we want. Only the first argument is required.

We can use the splice method to first remove the entry that we want to replace by getting the index of the item that we want to replace, and then we can use the splice method to insert a new entry in its place like in the following code:

const arr = ['apple', 'orange', 'grape', 'banana'];
const index = arr.indexOf('orange');
arr.splice(index, 1);
arr.splice(index, 0, 'chicken');
console.log(arr);

If we run the code above, we should get the same output as we did before:

["apple", "chicken", "grape", "banana"]

The first two lines are the same as the first example. Then, we called the splice method the first time to remove the original entry in the index. The first argument is the index of the array we want to remove, and the second specifies that we only remove one entry, which is the entry specified by the index. Then we call splice again to insert the new entry in its place. We pass in index again in the second splice call since we want to insert the new element in the same place as the original. The second argument is zero since we don’t want to remove any entry. Then, we pass in 'chicken' in the third argument so that we get 'chicken' in the same position that 'orange' was in.

Map Array Entries From One Value to Another

If we want to map each entry of an array to a new value, we can do it in a few ways. We can either use the map method or the Array.from method do to this. The map method is an array instance method that takes a callback function that has up to three parameters. The first parameter is the value of the array that’s being processed by the map method. This is a required parameter. The second parameter is an optional parameter, which is the index of the array entry that’s being processed in the array. The third argument is the array of which the map method is being called on. The callback returns the value that we want the new value to have.

For example, if we want to get a field of each array entry into a new array, we can write the following code:

const arr = [{
    food: 'apple',
    color: 'red'
  },
  {
    food: 'orange',
    color: 'orange'
  },
  {
    food: 'grape',
    color: 'purple'
  },
  {
    food: 'banana',
    color: 'yellow'
  }
];
const foodColors = arr.map(({
  color
}) => color);
console.log(foodColors);

In the code above, we used the map method to get the value of the color field and put it in a new array. In the map method, we passed in a callback function with the first parameter, with the objects in the arr array destructured into color variable, and the color variable is retrieved within the parameter then we returned it. This is will get us the value of the color field of each entry into the new foodColors array.

Alternatively, we can use the Array.from method to do the same thing. The Array.from method creates a new shallow copied array instance from an array-like or other iterable objects. The first argument that it accepts is an array or other array-like or iterable objects like NodeList, arguments , strings, TypedArrays like Uinit8Array, Map, other Sets, and any other object that have a Symbol.iterator method. The second argument is an optional callback argument function we can use to map each entry from one value to another. The callback function takes two parameters, which is the entry that’s being processed by the from method. The from method will iterate through the whole iterable object or array to map each entry to a new value. The second parameter is the index of the array or iterable that’s being processed. It returns a new array with the new entry

For example, we can replace the map method with the Array.from method with the following code:

const arr = [{
    food: 'apple',
    color: 'red'
  },
  {
    food: 'orange',
    color: 'orange'
  },
  {
    food: 'grape',
    color: 'purple'
  },
  {
    food: 'banana',
    color: 'yellow'
  }
];
const foodColors = Array.from(arr, ({
  color
}) => color);
console.log(foodColors);

In the code above, we used the callback function that we passed into the Array.from method to get the value of the color field and put it in a new array. In the map method, we passed in a callback function with the first parameter, with the objects in the arr array destructured into color variable. The color variable is retrieved within the parameter, then we returned it. This will get us the value of the color field of each entry into the new foodColors array.

There are a few ways to replace specific values from an array. We can use the indexOf method to get the first occurrence of an array and then use the index to assign a new value to the entry in that array index. We can also use the splice method to remove the existing entry given the index, and then add another element to the same position given the same index. If we want to map each entry of an array to a new value, we can do it in a few ways. We can either use the map method or the Array.from method do to this.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

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