Categories
JavaScript Answers

How to Delete Duplicate Elements From an Array with JavaScript?

Sometimes, we want to delete duplicate elements from an array with JavaScript.

In this article, we’ll look at how to delete duplicate elements from an array with JavaScript.

Delete Duplicate Elements From an Array with JavaScript

To delete duplicate elements from an array with JavaScript, we can use the array filter method or the Set constructor with the spread operator.

For instance, we can use the array filter method by writing:

const arr = [1, 2, 2, 3, 4, 5, 5, 5, 6, 7, 7, 8, 9, 10, 10]
const unique = arr.filter((elem, index, self) => {
  return index === self.indexOf(elem);
})
console.log(unique)

We call filter with a callback that checks if index is the same as the index returned by indexOf called on the self array with elem .

If it’s not the first instance of elem , then they’ll be different.

self is the same as arr .

Therefore, duplicate instances of elem won’t be present in arr .

So unique is:

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

Likewise, we can use the Set constructor with the spread operator to remove the duplicates.

For instance, we can write:

const arr = [1, 2, 2, 3, 4, 5, 5, 5, 6, 7, 7, 8, 9, 10, 10]
const unique = [...new Set(arr)]
console.log(unique)

We pass arr into the Set constructor to convert arr to a set to remove the duplicate elements.

Then we spread that back into an array to convert the set back into an array.

And therefore, unique is the same result as before.

Conclusion

To delete duplicate elements from an array with JavaScript, we can use the array filter method or the Set constructor with the spread operator.

Categories
JavaScript Answers

How to Automatically Add Properties to an Object that is Undefined with JavaScript?

Sometimes, we want to automatically add properties to an object that is undefined with JavaScript.

In this article, we’ll look at how to automatically add properties to an object that is undefined with JavaScript.

Automatically Add Properties to an Object that is Undefined with JavaScript

To automatically add properties to an object that is undefined with JavaScript, we can use the hasOwnProperty method to check if a property exists.

It’ll return true if it exists and false otherwise.

If it returns false , then we can set the property value to the value we want.

For instance, we can write:

const test = {}  
if (!test.hasOwnProperty('hello')) {  
  test.hello = {};  
}  
test.hello.world = "Hello World!"

We have the test object that we want to add the hello property to if it doesn’t exist.

We check that it doesn’t exist with !test.hasOwnProperty(‘hello’) .

And if that’s true , we set test.hello to an empty object.

Then we set test.hello.world to “Hello World!” .

The hasOwnProperty method can be overridden easily since it’s inherited from the Object constructor.

Therefore to make sure we always call the right hasOwnProperty method, we can write:

const test = {}  
if (!Object.prototype.hasOwnProperty.call(test, 'hello')) {  
  test.hello = {};  
}  
test.hello.world = "Hello World!"

We call Object.prototype.hasOwnProperty.call with test to do the same thing as test.hasOwnProperty , but we make sure that we always call the right one from the Object constructor.

Conclusion

To automatically add properties to an object that is undefined with JavaScript, we can use the hasOwnProperty method to check if a property exists.

It’ll return true if it exists and false otherwise.

If it returns false , then we can set the property value to the value we want.

Categories
JavaScript Answers

How to Tell setInterval to Only Fire x Amount of Times with JavaScript?

Sometimes, we want to tell setInterval to only fire x amount of times with JavaScript.

In this article, we’ll look at how to tell setInterval to only fire x amount of times with JavaScript.

Tell setInterval to Only Fire x Amount of Times with JavaScript

To tell setInterval to only fire x amount of times with JavaScript, we can keep track of the number of times the setInterval callback is called.

Then when the limit is reached, we can call clearInterval to stop the setInterval timer.

For instance, we can write:

let x = 0;  
const intervalID = setInterval(() => {  
  if (++x === 5) {  
    window.clearInterval(intervalID);  
  }  
  console.log('hello')  
}, 200);

to keep track of the number of times the setInterval callback is called with x .

Then we call setInterval with a callback that increments x with ++ in front to return the value of x after incrementing by 1.

Next, we check if x is 5 to top the timer with clearInterval when the setInterval callback has been called 5 times.

clearInterval is called with the intervalID to stop the timer.

And then we call console log to log some message.

200 is the number of milliseconds between each setInterval call.

As a result, the setInterval callback will be called 5 times only.

Conclusion

To tell setInterval to only fire x amount of times with JavaScript, we can keep track of the number of times the setInterval callback is called.

Then when the limit is reached, we can call clearInterval to stop the setInterval timer.

Categories
JavaScript Answers

How to Disable the Submit Button on Form Submission with JavaScript?

Sometimes, we want to disable submit button on form submission with JavaScript.

In this article, we’ll look at how to disable submit button on form submission with JavaScript.

Disable the Submit Button on Form Submission with JavaScript

To disable submit button on form submission with JavaScript, we can listen to the submit event of the form.

Then we can set the disabled attribute of the submit button to true when we submit the form.

For instance, if we have the following HTML form:

<form>
  <input>
  <input type='submit'>
</form>

Then we can write the following JavaScript to disable the submit button when we submit the form with jQuery by writing:

$('form').submit(function() {
  $(this).find(':input[type=submit]').prop('disabled', true);
});

We get the form with $(‘form’) .

Then we call submit on it with a callback to listen to the submit event of the form.

The callback we pass into submit get the submit button of the form with $(this).find(‘:input[type=submit]’) .

Then we call prop with 'disabled' and true to disable the form’s submit button.

Conclusion

To disable submit button on form submission with JavaScript, we can listen to the submit event of the form.

Then we can set the disabled attribute of the submit button to true when we submit the form.

Categories
JavaScript Answers

How to Detect if an HTML5 Video Element is Playing with JavaScript?

Sometimes, we want to detect if an HTML5 video element is playing with JavaScript.

In this article, we’ll look at how to detect if an HTML5 video element is playing with JavaScript.

Detect if an HTML5 Video Element is Playing with JavaScript

To detect if an HTML5 video element is playing with JavaScript, we can listen to various events emitted by the HTML5 video element.

To do this, we can add the video element with the following HTML:

<div id="output"></div>
<video id="myVideo" width="320" height="176" controls autoplay>
  <source src="https://file-examples-com.github.io/uploads/2017/04/file_example_MP4_480_1_5MG.mp4" type="video/mp4">
</video>

to add a div to show some text when various events are triggered.

Then we add a video element with the video.

Next, we add the following JavaScript code to listen to video player events and set the div content according to the event triggered:

const media = document.getElementById('myVideo');
const output = document.getElementById('output');

media.addEventListener("playing", () => {
  output.innerHTML = "Playing event triggered";
});

media.addEventListener("pause", () => {
  output.innerHTML = "Pause event triggered";
});

media.addEventListener("seeking", () => {
  output.innerHTML = "Seeking event triggered";
});

media.addEventListener("volumechange", () => {
  output.innerHTML = "Volumechange event triggered";
});

We get the video and div elements with document.getElementById .

Then we call addEventListener on the video player to listen to various events emitted by it.

The 'playing' event is emitted when the video is playing.

The 'pause' event is emitted when the video is paused.

The 'seeking' event is emitted when we’re moving the seek bar.

The 'volumechange' event is emitted when the video volume is changed.

In the event handlers, we set the innerHTML of the div to the content we want to display.

Conclusion

To detect if an HTML5 video element is playing with JavaScript, we can listen to various events emitted by the HTML5 video element.