Categories
JavaScript Answers

How to Generate a Range of Numbers within the Supplied Bounds?

There’re occasions where we need to generate an array of numbers within the given bounds.

In this article, we’ll look at how to generate a range of numbers within the supplied bounds.

The Array function

We can use the Array constructor as a regular function to create an array with the given size.

Then we can get the indexes with the keys method to get the indexes of an array.

For instance, we can write:

const arr = [...Array(5).keys()];
console.log(arr)

We call keys to return the indexes of the array.

And we spread the items into an array.

Array.from

The Array.from method is a static method that lets us create an array derived from another array.

We can use it to create a number array by using it to map the values to the ones we want.

For instance, we can write:

const lowerBound = 6;
const arr = Array.from(new Array(10), (x, i) => i + lowerBound);
console.log(arr)

The first argument is the array we want to map from.

And the 2nd argument is the mapping function.

x is the entry in from the array in the first argument we’re iterating through.

And therefore, we get:

[6, 7, 8, 9, 10, 11, 12, 13, 14, 15]

as the value of arr .

Lodash

Lodash has the range method that lets us create an array with a range of numbers easily.

It takes up to 3 arguments.

The first is the size of the array to create if there’s only one argument.

If we pass in 2 arguments, then the first number is the starting number and the 2nd is the ending number.

And if we pass in 3 arguments, then the first and 2nd arguments are the same as passing in 2 arguments.

And the 3rd argument is the increment between each number.

For instance, if we write:

const arr = _.range(10);
console.log(arr)

then arr is [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] .

If we write:

const arr = _.range(1, 11);
console.log(arr)

Then arr is [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] .

And if we write:

const arr = _.range(1, 11, 2);
console.log(arr)

then arr is [1, 3, 5, 7, 9] .

Conclusion

We can create an array of numbers with the Array function.

Also, we can use the Array.from static method.

Another easy way to create a number array is to use Lodash’s range method.

Categories
JavaScript Answers

How to Clear the Canvas for Redrawing?

If we have a canvas, we may want to clear it so that we can draw new things on it.

In this article, we’ll look at how to clear the canvas so that we can draw on it again.

Clear the Canvas for Redrawing

We can clear the canvas easily with the clearRect method, which is part of the canvas context object.

For instance, if we have the following HTML:

<canvas></canvas>
<button>
  clear
</button>

Then we can write:

const canvas = document.querySelector("canvas");
const button = document.querySelector("button");
const ctx = canvas.getContext("2d");
ctx.beginPath();
ctx.lineWidth = "6";
ctx.strokeStyle = "green";
ctx.rect(5, 5, 290, 140);
ctx.stroke();

button.addEventListener('click', () => {
  ctx.clearRect(0, 0, canvas.width, canvas.height);
})

to draw something and add a click listener to the button to clear the canvas when we click the button.

We call getContext to get the context object.

Then we call beginPath to start drawing.

And we set the lineWidth to set the width of the line.

strokeStyle sets the stroke style.

rect draws the rectangle with the x and y coordinates of the top left corner and the width and height respectively.

And the stroke method draws the rectangle.

Next, we call addEventListener with the 'click' to add a click listener to the button.

And the callback runs when we click the button.

We call clearRect with the canvas context with the same arguments as rect .

It clears the canvas instead of drawing on it.

Transformed Coordinates

If we added coordinate transformations to our canvas, then we’ve to add more code to save the transformation matrix first.

Then we can clear the canvas, and then restore the transformation matrix.

To do this, we write:

const canvas = document.querySelector("canvas");
const button = document.querySelector("button");
const ctx = canvas.getContext("2d");
ctx.beginPath();
ctx.lineWidth = "6";
ctx.strokeStyle = "green";
ctx.rect(5, 5, 290, 140);
ctx.stroke();

button.addEventListener('click', () => {
  ctx.save();
  ctx.setTransform(1, 0, 0, 1, 0, 0);
  ctx.clearRect(0, 0, canvas.width, canvas.height);
  ctx.restore();
})

In the callback, we call save to save the transformation matrix.

setTransform set the transformation to the identity matrix to remove the transformation.

Then we call clearRect to clear the canvas.

And we call restore to restore the transformation.

Conclusion

We can clear the canvas by calling the clearRect method.

If we have transformed coordinates, then we can save the transformation matrix, clear the canvas, and then restore the transformation matrix.

Categories
JavaScript Answers

How to Extend an Existing JavaScript Array With Another Array Without Creating a New Array?

Adding items from another array to a JavaScript array is an operation that we’ve to do a lot.

In this article, we’ll look at how to add items from an existing JavaScript array to another array.

Array.prototype.push

We can call the push method to add items to an existing array.

And we can pass in as many arguments as we want to add as many items as we want.

Therefore, we can use the spread operator to spread the items from an array in the push method to spread the array into push as arguments.

For instance, we can write:

const array1 = [1, 2, 3]
const array2 = [4, 5, 6]
array1.push(...array2)
console.log(array1)

Then array1 is [1, 2, 3, 4, 5, 6] .

We can use the spread operator since ES6.

Alternatively, we can use apply to with push to append items from one array in an existing array:

const array1 = [1, 2, 3]
const array2 = [4, 5, 6]
array1.push.apply(array1, array2)
console.log(array1)

apply takes the value of this as the first argument.

And the 2nd argument is an array of arguments for push .

Therefore array1 is the same as in the previous example at the end.

We can also write:

const array1 = [1, 2, 3]
const array2 = [4, 5, 6]
Array.prototype.push.apply(array1, array2)
console.log(array1)

to do the same thing.

Array.prototype.concat

Also, we can call concat to append items from one array in an existing array.

To do this, we write:

let array1 = [1, 2, 3]
const array2 = [4, 5, 6]
array1 = array1.concat(array2)
console.log(array1)

All the items from array2 are added to array1 .

Since concat returns a new array, we’ve to assign the returned result back to array1 .

And so we get the same result as the other examples.

Spread Operator

We can just use the spread operator to spread items from one array into another.

To use it, we write:

let array1 = [1, 2, 3]
const array2 = [4, 5, 6]
array1 = [...array1, ...array2]
console.log(array1)

We spread the items from array1 and array2 into a new array.

Then we assign that result back to array1 .

And so we get the same result as before.

Conclusion

We can use the spread operator or array methods to add array items into another array.

Categories
JavaScript Answers

How to Compare Arrays in JavaScript?

Comparing if 2 arrays are the same is something that we’ve to do sometimes in our JavaScript app.

In this article, we’ll look at how to compare arrays with JavaScript.

Array.prototype.every

We can use the array’s every method to check if every element in one array is also in the array we’re comparing against.

If they have the same length and each element in one array is also in the other, then we know that both arrays are the same.

For example, we’ll write:

const array1 = [1, 2, 3]
const array2 = [1, 2, 3]
const sameArray = array1.length === array2.length && array1.every((value, index) => value === array2[index])
console.log(sameArray)

We have 2 array array1 and array2 that have the same contents.

Then we check if both have the same length.

And then we call every with the callback to compare value with array2[index] .

value has the array1 entry we’re iterating through.

index has the index of the array1 entry we’re iterating through.

And so we can use index to get the element from array2 and compare them.

Lodash isEqual Method

We can also use Lodash’s isEqual method to compare 2 arrays to see if they have the same content.

For instance, we can write:

const array1 = [1, 2, 3]
const array2 = [1, 2, 3]
const sameArray = _.isEqual(array1, array2)
console.log(sameArray)

We just pass in the arrays we want to compare as the arguments.

JSON.stringify

Also, we can do simple array comparisons with the JSON.stringify method.

It’ll convert the array to a JSON string.

Then we can compare the stringified arrays directly.

For instance, we can write:

const array1 = [1, 2, 3]
const array2 = [1, 2, 3]
const sameArray = JSON.stringify(array1) === JSON.stringify(array2);
console.log(sameArray)

Conclusion

There’re several ways we can use to compare if 2 arrays are the same with JavaScript.

The easiest way is to use JSON.stringify to compare the stringified versions of the arrays.

Also, we can use the every method to check each item of an array to see if they’re the same.

Finally, we can use the Lodash isEqual method to compare 2 arrays.

Categories
JavaScript Answers

How to Check if a JavaScript String Ends with a Given String?

Checking if a JavaScript string ends with a given string is something that we may have to do sometimes.

In this article, we’ll look at how to check if a JavaScript string ends with a given string.

String.prototype.indexOf

We can use the string’s indexOf method to check the index of the string.

For instance, we can write:

const endsWith = (str, suffix) => {  
  return str.indexOf(suffix, str.length - suffix.length) !== -1;  
}  
console.log(endsWith('hello world', 'world'))

We call indexOf with the suffix , which is the string we’re searching for.

And we start searching from the index str.length — suffix.length .

This will make sure the suffix is at the end if it exists.

If indexOf returns anything other than -1, then suffix is at the end of the string.

Otherwise, it’s not at the end of the string.

Using the substr Method

We can use the substr method to check whether a substring is at the location we want.

To do this, we write:

const endsWith = (str, suffix) => {  
  return str.length >= suffix.length && str.substr(str.length - suffix.length) === suffix;  
}  
console.log(endsWith('hello world', 'world'))

In the endsWith function, we check if str.length >= suffix.length so that we know str is longer than suffix .

If that’s true , then we call substr with str.length — suffix.length to get the substring starting with index str.length — suffix.length which is where the suffix would start if it’s at the end.

If the returned value is equal to suffix , then we know suffix is at the end of str .

Using the lastIndexOf Method

Also, we can use the lastIndexOf method to get the index of the last instance of a given substring.

For instance, we can write:

const endsWith = (str, suffix) => {  
  const lastIndex = str.lastIndexOf(suffix);  
  return (lastIndex !== -1) && (lastIndex + suffix.length === str.length);  
}  
console.log(endsWith('hello world', 'world'))

We call lastIndexOf with suffix to get the index of the start of the last instance of suffix .

Then if lastIndex isn’t -1 and that lastIndex + suffix.length is the same as str.length , we know suffix is located at the end of str .

String.prototype.endsWith

Strings come with the endsWith method that lets us check whether the string we called the method on ends with a given substring.

For instance, we can write:

console.log('hello world'.endsWith('world'))

We just call endsWith with the substring we’re checking for.

Conclusion

We can check if a string ends with a given substring with various string methods.