Categories
JavaScript Answers

How to Truncate Arrays with JavaScript?

In JavaScript, array objects have a length property that specifies the length of an array. It’s both a getter and setter property so in addition to being able to get the length of an array, we can also use it to set the length of an array.

Setting the length property to be less than the original length of the array will truncate the array up to the number of entries that we specify. For example, if we want to only keep the first entry of an array, then we can write something like:

let arr = [1, 2, 3, 4, 5, 6];
arr.length = 1
console.log(arr);

We simply set the length property of our array and then magically we get only the first element of the array left.

Alternatively, we can use the splice method to remove entries from an array. This method lets us removing, replace an existing element or adding new elements in place, but we only need it to delete elements from the array.

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.

For example, if we want to truncate an array and keep only the first 2 elements, we can write something like the following code:

const arr = [1, 2, 3, 4, 5, 6];
arr.splice(2)
console.log(arr);

As we can see we only need to specify the first argument, and then the deleteCount will be automatically set so that it removes the entries on the right of the array. We can also specify a negative start index like in the following code:

const arr = [1, 2, 3, 4, 5, 6];
arr.splice(-1 * arr.length + 1)
console.log(arr);

So if we specify -1 * arr.length + n in the first argument, then we keep the first n entries of the original array.

We can also use the slice method to truncate arrays. It’s used for extracting values from an array in general and returns a new array with the extracted values. The slice method takes 2 arguments.

The first is an optional argument to specify where to begin extracting entries from an array. The second argument is another optional argument that specifies the end index of the original array to end the extraction of values from it. The value at the end index itself is excluded from the extraction.

For example, if we want the first 2 values from the original array, then we can write something like the following code:

let arr = [1, 2, 3, 4, 5, 6];
arr = arr.slice(0, 2);
console.log(arr);

When we run the code, we get back [1, 2] as the new value of arr . We can also specify negative indexes for the start and end. The last entry of the array is at -1, the second last element is at the index -2, and so on. So if we want to extract the first 2 elements of an array with negative indexes, we can write something like the following:

let arr = [1, 2, 3, 4, 5, 6];
arr = arr.slice(-1 * arr.length, -1 * arr.length + 2);
console.log(arr);

The first element of an array would be at index -1 * arr.length if we expressed it in terms of a negative index. Then the subsequent entries would be at -1 * arr.length + n where n is array entry at the n th position.

Categories
JavaScript Answers

How to Map Array Entries From One Value to Another with JavaScript?

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.

Categories
JavaScript Answers

How to Replace Specific Value From an Array with JavaScript?

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.

Categories
JavaScript Answers

How to Shuffle an Array of Numbers with JavaScript?

With the sort method built into the JavaScript array objects, we can use it easily to sort arrays. The sort method takes a function that lets us compare 2 entries in the array to let us set the sort order between 2 elements based on the conditions that we specify.

The function that we pass into the sort method takes 2 parameters, the first is an element which we call a, and the second is an element which we call b, and we compare a and b to determine which should be sorted above the other in the array. The sort function expects a number to be returned by the callback.

If the value that’s returned by our function is negative, then a will be in an array index that’s lower than b. That is, a comes before b. If the number is positive, then b will come before a. If the function returns 0, then a and b will stay in their original position.

If we want to shuffle the array, we can just return a random number from it — the value of a or b will not have an impact on the sort. We can once again use the Math.random() method to help us generate a random return value for the function we pass into the sort method. We can write the following code to sort each entry in random order (shuffle the array):

let nums = [49, -151, 88, -133, -164, 78, 117, -25, 76, -40];
nums = nums.sort(() => {
  return Math.random() - 0.5
});
console.log(nums);

In the code above, our sort method has a function which generates a random number between -0.5 and 0.5, which means there’s a chance that each element either stays in place or gets shuffled, according to what the sort method will do depending on the return value.

The Math.random() only returns numbers between 0 and 1. However, we can easily make it more useful by extending it in the ways that we did above. We can specify a range between a minimum and a maximum number and Math.random() * (max — min) + min to generate a number between a range. Also, we can pass it into the callback function of the sort method by returning Math.random() — 0.5 to generate a number between -0.5 and 0.5, which means that it can be shuffled (or not) depending on the sign of the generated number and whether it’s 0 or not.

Categories
JavaScript Answers

How to Generate an Array of Random Numbers with JavaScript?

We can easily expand the code above to generate an array of random numbers. Using the Array.from method that we used above, we can create the array like in the following code:

const arr = Array.from({
  length: 10
}, (v, i) => {
  const min = 1;
  const max = 10;
  return Math.random() * (max - min) + min
});
console.log(arr)

In the second argument of the Array.from method call, we modified the function for mapping the values to the number generator function with the code inside it as the same code that we used to generate random numbers.

Again, we can specify the length property of the object in the first argument to the length of the array that we want. If we run the code above, the console.log output from the statement on the last line should log something like:

[2.09822597784169, 9.485219511793478, 4.905513590655689, 5.428402066955793, 5.874266428138649, 6.288415362686418, 2.768483595321933, 9.849179787675595, 1.1291148797430082, 6.725810669834928]

Also, we can use the integer generator code that we have before in the same manner, like in the code below:

const arr = Array.from({
  length: 10
}, (v, i) => {
  let min = 1;
  let max = 10;
  min = Math.ceil(min);
  max = Math.floor(max);
  return num = Math.floor(Math.random() * (max - min)) + min;
});
console.log(arr)

We have the same code that we used to generate integers as before, except that we used it to generate an array of random integers. If we run the code above, we should get something like the following:

[8, 3, 5, 4, 4, 9, 9, 1, 1, 1]

from the console.log statement above.