Categories
JavaScript Answers

How to create and clone a JSON object with JavaScript?

To create and clone a JSON object with JavaScript, we can use the spread operator.

For instance, we write

const newJsonObj = { ...jsonObj };

to shallow copy the properties of the jsonObj object into a new object and assign the new object to newJsonObj.

Categories
JavaScript Answers

How to add a dotted stroke in the JavaScript canvas?

To add a dotted stroke in the JavaScript canvas, we call the setLineDash method.

For instance, we write

const c = document.getElementById("myCanvas");
const ctx = c.getContext("2d");

ctx.setLineDash([5, 10]);

ctx.beginPath();
ctx.lineWidth = "2";
ctx.strokeStyle = "green";
ctx.moveTo(0, 75);
ctx.lineTo(250, 75);
ctx.stroke();

to call setLineDash with the dash stroke lengths.

Then we call beginPath to start drawing.

We set the line width by setting lineWidth.

We set the stroke color by setting strokeStyle.

Then we draw by calling moveTo with the start point.

We call lineTo to draw to the end point.

And we call stroke to stop drawing.

Categories
JavaScript Answers

How to calculate median with JavaScript?

To calculate median with JavaScript, we can sort the numbers and get the middle value.

For instance, we write

const median = (numbers) => {
  const sorted = Array.from(numbers).sort((a, b) => a - b);
  const middle = Math.floor(sorted.length / 2);

  if (sorted.length % 2 === 0) {
    return (sorted[middle - 1] + sorted[middle]) / 2;
  }

  return sorted[middle];
};

console.log(median([4, 5, 7, 1, 33]));

to define the median function.

In it, we call sort on the copied numbers array after copying it with Array.from to sort the numbers in ascending order.

Then we check if the length of the sorted array is event.

We get the middle index by taking the floor of the length divided by 2.

If it is, then we take the average of the 2 middle numbers.

Otherwise, we return the middle number.

Categories
JavaScript Answers

How to fix function being called twice in React?

To fix function being called twice in React, we disable strict mode.

For instance, if we have

<React.StrictMode>
  <App />
</React.StrictMode>

then we disable strict mode by removing the React.StrictMode component from the code.

Categories
JavaScript Answers

How to convert milliseconds to hours and minutes using Moment.js and JavaScript?

To convert milliseconds to hours and minutes using Moment.js and JavaScript, we use the duration method.

For instance, we write

const x = 433276000;
const tempTime = moment.duration(x);
const hours = tempTime.hours();
const minutes = tempTime.minutes();

to call duration with the number of milliseconds to convert it to a duration object.

Then we call hours to get the number of hours and minutes to get the number of minutes.