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.

Categories
JavaScript Answers

How to Call Javascript Array’s reduce Method on an Array of Objects?

Sometimes, we’ve to call the JavaScript array’s reduce method on an array of objects and we want to get a result from it.

In this article, we’ll look at how to JavaScript array’s reduce method to produce a result and put it in an object.

Calling reduce on an Array of Objects

To call reduce on an array of objects, we can get the object from the callback.

To do this, we write:

const arr = [{
  x: 1
}, {
  x: 2
}, {
  x: 3
}];
const result = arr.reduce((a, b) => ({
  x: a.x + b.x
}));
console.log(result)

We have the arr array.

And we call reduce on it with a callback by returning an object with the x property and the x property from a and b added together.

a and b are the objects that are from the arr array.

We can also get the value of the x property and just add them together.

For instance, we can write:

const arr = [{
  x: 1
}, {
  x: 2
}, {
  x: 3
}];
const result = arr.reduce((acc, obj) => {
  return acc + obj.x;
}, 0);
console.log(result)

acc is the sum of all the x property values together.

obj has the object in arr that we’re iterating through.

We return acc + obj.x to return the sum.

The 2nd argument is the initial value of the returned result.

We set it to 0 so that we can add the x values together.

And so result is 6.

Also, we can destructure the object in the 2nd parameter of the callback by writing:

const arr = [{
  x: 1
}, {
  x: 2
}, {
  x: 3
}];
const result = arr.reduce((acc, { x }) => {
  return acc + x;
}, 0);
console.log(result)

Using map and reduce Together

Also, we can use the map and reduce methods together.

We use map to return an array of numbers from the x property.

And then we can use reduce to add all the numbers together.

For instance, we can write:

const arr = [{
  x: 1
}, {
  x: 2
}, {
  x: 3
}];
const result = arr.map((a) => a.x)
  .reduce((a, b) => a + b);
console.log(result)

We call map with a callback to return the value of x .

And then we call reduce with a callback to return the sum.

Conclusion

We can call reduce on an array of objects by getting the object from the parameter and do what we want with it.

Or we can use map to extract the values we want from the array entries and call reduce to combine the values the way we want.

Categories
JavaScript Answers

How to Inspect the JavaScript FormData Instance?

If we have an HTML form, then the entered data may be stored in an object that’s created from the FormData instance.

In this article, we’ll look at how to inspect the object created from the FormData constructor.

The for-of Loop with the entries Method

We can use the for-of loop to loop through the key-value pairs of the FormData instance to inspect their values.

To get the key-value pairs, we can use the entries method of the FormData instance to return the key-value pairs in an array.

For example, we can write:

const formData = new FormData();
formData.append('key1', 'value1');
formData.append('key2', 'value2');

for (const [key, value] of formData.entries()) {
  console.log(key, value);
}

Then we get:

key1 value1
key2 value2

We create the formData object with the FormData constructor.

Then we call append with the key and value respectively to add the entry to the formData object.

Next, we call formData.entries to return an array with the key-value pairs in an array.

In the for-of loop, we destructure the key-value pairs and log them with console.log .

Omit the entries Method

We can omit the entries method since formData is an iterable object.

It has an iterator to return the key-value pairs.

Therefore, we can shorten it to:

const formData = new FormData();
formData.append('key1', 'value1');
formData.append('key2', 'value2');

for (const [key, value] of formData) {
  console.log(key, value);
}

Object.fromEntries

We can also use Object.fromEntries to get the key-value pairs into an object that we can inspect easily.

This works because it a FormData instance has an iterator that returns the key-value pair arrays in an array.

For instance, we can write:

const formData = new FormData();
formData.append('key1', 'value1');
formData.append('key2', 'value2');
console.log(Object.fromEntries(formData))

Then we get:

{key1: "value1", key2: "value2"}

from the console log.

Using the Response Constructor

We can use the Response constructor to convert the FormData instance to text we can inspect easily.

For instance, we can write:

const formData = new FormData();
formData.append('key1', 'value1');
formData.append('key2', 'value2');

(async () => {
  const text = await new Response(formData).text()
  console.log(text)
})()

The text method returns a promise, so we put it in an async function.

Then text is something like:

------WebKitFormBoundaryzCHPG30oZJEPIn1B
Content-Disposition: form-data; name="key1"

value1
------WebKitFormBoundaryzCHPG30oZJEPIn1B
Content-Disposition: form-data; name="key2"

value2
------WebKitFormBoundaryzCHPG30oZJEPIn1B--

If we only care about inspecting it, then we can use the text method.

Conclusion

There’re several ways to inspect a FormData instance.

It’s an iterable object, so we can use the for-of loop with it.

Also, we can convert it to a Response instance and use the text method to inspect it.