Categories
JavaScript Answers

How to Get JSON Data from a URL in JavaScript?

On many occasions, we want to get JSON data from a URL with JavaScript.

In this article, we’ll look at how to get JSON data from a URL with JavaScript.

Use the Fetch API

The Fetch API lets us make HTTP requests easily within the browser.

It’s promise-based and we can use it to get JSON data easily.

This means we can make multiple requests sequentially easily.

For instance, we can write:

fetch('https://yesno.wtf/api')  
  .then(res => res.json())  
  .then((out) => {  
    console.log(out);  
  })  
  .catch(err => {  
    throw err  
  });

to make a GET request to the URL we pass into fetch .

Then we can res.json in the then callback to convert the response to a JSON object and return a promise with that.

Next, we get the result from the parameter from the 2nd promise callback.

And so we get something like:

{answer: "yes", forced: false, image: "https://yesno.wtf/assets/yes/11-a23cbde4ae018bbda812d2d8b2b8fc6c.gif"}

for out .

We can also use the async and await syntax to make this shorter.

The catch method lets us catch any request errors that arise.

For instance, we can write:

(async () => {  
  try {  
    const res = await fetch('https://yesno.wtf/api')  
    const out = await res.json()  
    console.log(out);  
  } catch (err) {  
    throw err  
  }  
})()

We replaced the then callbacks with await .

And we replaced the catch method with the catch block.

Conclusion

We can use the Fetch API to get JSON data from a URL easily.

It’s a promised-based API which makes making multiple requests sequentially easy.

Categories
JavaScript Answers

How to Get the Closest Number to a Number Out of a JavaScript Array?

Sometimes, we may want to get the closest number to a given number out of a JavaScript array.

In this article, we’ll look at how to get the closest number to a number out of a JavaScript array.

Using the Array.prototype.reduce Method

One way to get the closest number to a number out of a JavaScript array is to use the JavaScript array’s reduce method.

To use it, we write:

const arr = [2, 42, 82, 122, 162, 202, 242, 282, 322, 362]
const goal = 100
const closest = arr.reduce((prev, curr) => {
  return (Math.abs(curr - goal) < Math.abs(prev - goal) ? curr : prev);
});
console.log(closest)

We have the arr array that has a bunch of numbers.

goal is the number that we want to find the closest number in arr from.

We then pass in the callback into the reduce method that compares the absolute value of the difference between curr — goal and prev-goal .

prev is the previously closest number to goal .

And curr is the current number that’s being iterated through.

If curr is closer to goal that prev in absolute value, then we return curr .

Otherwise, we return goal .

Therefore, closest is 82.

Use the Array.prototype.map Method

Another way to find the closest number to a given number is to map all the array entries to the absolute difference between the number in the array and the goal number.

Then we can use Math.min to find the minimum difference between the numbers.

For instance, we can write:

const arr = [2, 42, 82, 122, 162, 202, 242, 282, 322, 362]
const goal = 100
const indexArr = arr.map((num) => {
  return Math.abs(num - goal)
})
const min = Math.min(...indexArr)
const closest = arr[indexArr.indexOf(min)]
console.log(closest)

We call map with a callback that returns the absolute difference between num and goal .

Then we find the minimum of the differences with Math.min .

And then we get the index of the number with the lowest absolute difference with indexOf and pass that into arr to get the number that’s closest to goal .

So we get the same result as the previous example.

Conclusion

We can use JavaScript array and math methods to get the number that’s closest to the given number in an array with JavaScript.

Categories
JavaScript Answers

How to Detect URLs in a JavaScript String and Convert them to Links?

Use a Regex to Find URLs in a String

We can create our own function that uses a regex to find URLs.

For instance, we can write:

const urlify = (text) => {
  const urlRegex = /(https?:\/\/[^\s]+)/g;
  return text.replace(urlRegex, (url) => {
    return `<a href="${url}">${url}</a>`;
  })
}
const text = 'Find me at http://www.example.com and also at http://stackoverflow.com';
const html = urlify(text);
console.log(html)

We create the urlify functioon that takes a text string.

In the function, we refine the urlRegex variable that has the regex for matching URLs.

We check for http or https .

And we look for slashes and text after that.

The g flag at the end of the regex lets us search for all URLs in the string.

Then we call text.replace with the urlRegex and return a string with the matched url in the callback.

Therefore, when we call urlify with text , we get:

'Find me at <a href="http://www.example.com>http://www.example.com</a> and also at <a href="http://stackoverflow.com">http://stackoverflow.com</a>'

as a result.

We can make the URL search more precise with a more complex regex.

For instance, we can write:

const urlify = (text) => {
  const urlRegex = /(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig;
  return text.replace(urlRegex, (url) => {
    return `<a href="${url}>${url}</a>`;
  })
}
const text = 'Find me at http://www.example.com and also at http://stackoverflow.com';
const html = urlify(text);
console.log(html)

We search for http , https , ftp , and file URLs.

And we also include : , letters, ampersands, and underscores in the pattern.

Categories
JavaScript Answers

How to Swap Two Variables in JavaScript?

Sometimes in our JavaScript code, we’ve to swap the values of 2 variables in our code.

In this article, we’ll look at ways to swap 2 variables’ values in JavaScript.

Using Destructuring Syntax

One way to swap the value of 2 variables is to use the destructuring syntax.

For instance, we can write:

let a = 5,
  b = 6;
[a, b] = [b, a];
console.log(a, b);

We defined the a and b values which are 5 and 6 respectively.

Then in the 3rd line, we use the destructuring to swap their values.

On the right side, we put b and a into an array.

Then on the right side, we destructure the array entries by putting a and b on .the array on the left side.

So a is 6 and b is 5 when we long the values of a and b on the last line.

Using a Temporary Variable

We can also use a temporary variable to help swap the values of 2 variables.

To use it, we write:

let a = 1,
  b = 2,
  tmp;
tmp = a;
a = b;
b = tmp;
console.log(a, b);

We defined a and b which are 1 and 2 respectively.

Next, we assign a to the tmp temporary variable.

Then we assign b to a .

And finally, we assign the tmp to b to update b with the previous value of a .

Therefore, a is now 2 and b is 1.

Conclusion

We can swap the value of 2 variables with JavaScript by using the restructuring syntax or using a temporary variable.

Categories
JavaScript Answers

How to Format a Number with K at the End if it is One Thousand or More and Show the Number Otherwise in JavaScript?

Sometimes, we want to format a number so that we show K at the end if it’s a thousand or more and return the show number if it’s less than 1000.

In this article, we’ll look at how to format a number with K at the end if it’s 1000 or more and return the whole number otherwise.

Use Math Methods

We can create our own function that use Math methods to check if a number is 1000 or bigger in absolute value.

If it is, then we divide by 1000 and add a K after it.

Otherwise, we return the whole number.

To do this, we write:

const kFormatter = (num) => {
  return Math.abs(num) > 999 ? Math.sign(num) * ((Math.abs(num) / 1000).toFixed(1)) + 'k' : Math.sign(num) * Math.abs(num)
}

console.log(kFormatter(1200));
console.log(kFormatter(-1200));
console.log(kFormatter(900));
console.log(kFormatter(-900));

We create the kFormatted function that takes the num number parameter.

Then we check if num is bigger than 999 in absolute value.

Math.abs lets us compute the absolute value of a number.

If it’s bigger than 999, then we use Math.sign to get the sign of the number.

Math.sign return -1 if the number is negative and 1 otherwise.

Then we multiply that by the absolute value of num divided by 1000.

And then we call toFixed with 1 to return a string version of the number rounded to one decimal place.

Then we add 'k' after it.

Otherwise, we just return the number itself with:

Math.sign(num) * Math.abs(num)

So we get:

1.2k
-1.2k
900
-900

from the console log results.

Conclusion

We can use various Math methods to format numbers to return a truncated number if it’s 1000 or more and return the whole number otherwise.