Categories
JavaScript Answers

How to do Case Insensitive JavaScript String Comparison?

Sometimes, we’ve to case-insensitive JavaScript string comparison in our code.

In this article, we’ll look at how to do a case-insensitive JavaScript string comparison.

Convert Both Strings to Upper Case

One way to do a case-insensitive string comparison with JavaScript is to compare them both after converting them to upper case.

For instance, we can write:

const string1 = 'abc'  
const string2 = 'Abc'  
const areEqual = string1.toUpperCase() === string2.toUpperCase();  
console.log(areEqual);

We have string1 and string2 that have the same letter but with different cases.

Then we convert them both to upper case with the toUpperCase method.

And then we log the value of areEqual .

The console log should log true since they’re both the same when converted to upper case.

Convert Both Strings to Lower Case

We can convert both strings to lower case and do our comparisons that way.

For instance, we can write:

const string1 = 'abc'  
const string2 = 'Abc'  
const areEqual = string1.toLowerCase() === string2.toLowerCase();  
console.log(areEqual);

Then areEqual should be true since they’re the same when they’re both converted to lower case.

The localeCompare Method

We can use the JavaScript string’s localeCompare method to do case-insensitive string comparisons.

If they’re the same, then it returns 0.

For instance, we can write:

const string1 = 'abc'  
const string2 = 'Abc'  
const areEqual = string1.localeCompare(string2, undefined, {  
  sensitivity: 'base'  
});  
console.log(areEqual);

We call localeCompare on string1 and pass string2 into the first argument to compare them.

Then in the 3rd argument, we pass in an object with the sensitivity set to 'base' to ignore the case when comparing.

Then areEqual should be 0 since they’re the same when the case is ignored.

Conclusion

To do a case-insensitive comparison with 2 JavaScript strings, we can convert both strings to upper case or lower case.

Also, we can use the string localeCompare method to compare both strings in a case-insensitive manner by setting the sensitivity setting.

Categories
JavaScript Answers

How to Create a Two-Dimensional Array in JavaScript?

Sometimes we’ve to create a 2-dimensional array in a JavaScript app.

In this article, we’ll look at how to create 2-dimensional arrays with JavaScript.

Nested Arrays

In JavaScript, 2-dimensional arrays are just nested arrays.

For instance, we can write:

const arr = [
  [1, 2],
  [3, 4],
  [5, 6]
];
console.log(arr[0][0]);
console.log(arr[0][1]);
console.log(arr[1][0]);
console.log(arr[1][1]);
console.log(arr);

We have arrays in an array.

Then we can access the nested items with square brackets.

The first console log logs 1.

The 2nd console log logs 2.

The 3rd console log logs 3.

And the last console log logs 4.

Create an Empty Two Dimensional Array

To create an empty 2-dimensional array, we can use the Array.from and Array constructors.

For instance, we can write:

const arr = Array.from(Array(2), () => new Array(4))
console.log(arr);

The Array.from method lets us create an array from another array.

The first argument is the array we want to derive from the new array from.

And the 2nd argument is a function that maps the values from the first array to the values we want.

We return an array with 4 items.

Therefore, we get a 2×4 2-dimensional array returned.

Also, we can create a 2-dimensional array with just the Array function.

For instance, we can write:

const arr = Array(2).fill().map(() => Array(4));
console.log(arr);

We call the fill method to fill the empty slots.

This way, we can call map to and return arrays in the map callback to create the 2-dimensional array.

Conclusion

We can create JavaScript 2–dimensional arrays by nesting array literals.

Also, we can create 2-dimensional arrays with the Array function.

Categories
JavaScript Answers

How to Convert a Floating-Point Number to a Whole Number in JavaScript?

Converting a floating-point number to a whole number is something that we’ve to do sometimes in JavaScript apps.

In this article, we’ll look at how to convert a JavaScript floating-point number to a whole number.

Math.floor

The Math.floor method lets us round a number down to the nearest integer.

For instance, we can use it by writing:

const intvalue = Math.floor(123.45);  
console.log(intvalue)

Then we get 123 as the value of intValue .

Math.ceil

The Math.ceil method lets us round a number up to the nearest integer.

For instance, we can write:

const intvalue = Math.ceil(123.45);  
console.log(intvalue)

Then intValue is 124.

Math.round

The Math.round method lets us round a number down to the nearest integer if the first decimal digit is 4 or lower.

Otherwise, it rounds the number up to the nearest integer.

For instance, if we have:

const intvalue = Math.round(123.45);  
console.log(intvalue)

Then intValue is 123.

Math.trunc

The Math.trunc method lets us return the integer part of a number by removing the fractional digits.

For example, we can write:

const intvalue = Math.trunc(123.45);  
console.log(intvalue)

Then intValue is 123.

parseInt

The parseInt function lets us convert a floating-point number to an integer.

It works like Math.trunc in that it removes the fractional digits from the returned number.

For example, we can write:

const intvalue = parseInt(123.45);  
console.log(intvalue)

And intValue is 123.

To make sure that we return a decimal number, we pass 10 into the 2nd argument:

const intvalue = parseInt(123.45, 10);  
console.log(intvalue)

Conclusion

JavaScript provides a few functions and methods to lets us convert floating-point numbers to integers.

Categories
JavaScript Answers

How to Get the Name of a JavaScript Object’s Type?

Getting the name of the constructor that an object is created from is something that we’ve to sometimes.

In this article, we’ll look at how to get the name of the constructor that the JavaScript object is created from.

The constructor Property

We can use the constructor property of an object to get the constructor that it’s created from.

For instance, we can write:

const arr = [1, 2, 3];
console.log(arr.constructor === Array);

Then the console log logs true since the arr is created with the Array constructor.

This can also be used with constructors we create ourselves:

class A {}
const a = new A()
console.log(a.constructor === A);

The console log will also log true .

Inheritance

If we create an object from a subclass, then we can check if an object created from the current subclass.

For instance, we can write:

class A {}
class B extends A {}
const b = new B()
console.log(b.constructor === B);

Then the console log also logs true since b is created from the B constructor.

constructor has the name property to get the constructor name as a string.

For instance, we can write:

class A {}
const a = new A()
console.log(a.constructor.name === 'A');

to compare against the name of the constructor.

The instanceof Operator

The instanceof operator also lets us check if an object is created from a constructor.

For instance, we can write:

const arr = [1, 2, 3];
console.log(arr instanceof Array);

Then the console log should log true since arr is an array.

However, the Array.isArray is more reliable for checking if a variable is an array since it works across all frames.

Also, we can write:

class A {}
const a = new A()
console.log(a instanceof A);

to check if a is an instance of A .

instanceof also works with subclasses.

So we can write:

class A {}
class B extends A {}
const b = new B()
console.log(b instanceof B);

And it’ll log true .

Conclusion

We can use the instanceof operator and the constructor property to check if an object is created from the given constructor.

Categories
JavaScript Answers

How to Check if an Element is Visible After Scrolling?

Checking if an element is visible after scrolling is something that we may have to do sometimes.

In this article, we’ll look at how to check if an element is visible after scrolling with JavaScript.

Create Our Own Function

We can create our own function to check if an element is visible after scrolling.

For instance, we can write the following HTML:

<div>
</div>

And the following JavaScript:

const div = document.querySelector('div')
for (let i = 1; i <= 100; i++) {
  const p = document.createElement('p')
  p.id = `el-${i}`
  p.textContent = 'hello'
  div.appendChild(p)
}

const isScrolledIntoView = (el) => {
  const {
    top,
    bottom
  } = el.getBoundingClientRect();
  const elemTop = top;
  const elemBottom = bottom;
  const isVisible = (elemTop >= 0) && (elemBottom <= window.innerHeight);
  return isVisible;
}

const el = document.querySelector('#el-50')
document.addEventListener('scroll', (e) => {
  console.log(isScrolledIntoView(el))
})

We get the div element with querySelector .

Then we have a for loop to insert p elements into the div.

We set the id property so that we can get the inserted element later.

Next, we create the isScrolledIntoView function to check if the element is in the browser screen.

To do this, we call el.getBoundingClientRect to get the top and bottom coordinates of the element.

These are top and bottom y coordinates respectively.

Then we return the isVisible variable, which we create by checking if top is bigger than or equal to 0 and the bottom is less than or equal to the innerHeight of window.

If both conditions are true, then we know the element is in the window.

Then we get the element we want to watch with another querySelector call.

And finally, we call addEventListener to add the scroll event to the document and call the isScrolledIntoView function with the el element to see when el is in the browser window.

As we scroll down, we should see the logged value goes from false to true and back to false .

Using the IntersectionObserver API

The IntersectionObserver API is an API available in recent browsers to let us check whether an element is visible on the screen.

For instance, we can write:

const div = document.querySelector('div')
for (let i = 1; i <= 100; i++) {
  const p = document.createElement('p')
  p.id = `el-${i}`
  p.textContent = 'hello'
  div.appendChild(p)
}

const onIntersection = (entries, opts) => {
  entries.forEach(entry => {
    const visible = entry.intersectionRatio >= opts.thresholds[0]
    console.log(entry.intersectionRatio.toFixed(2), visible)
  })
}

const intersectionObserverOptions = {
  root: null,
  threshold: .5
}

const observer = new IntersectionObserver(onIntersection, intersectionObserverOptions)
const target = document.querySelector('#el-50')
observer.observe(target)

The first querySelector call and the for loop is the same as before.

Then we define the onIntersection function that takes the entries and opts parameters.

entries is the elements we’re watching for visibility with.

And opts is an options object that has the thresholds property to get the threshold of intersection with the screen.

In the forEach callback, we have the the visible variable, which we create by comparing the intersectionRatio of entry with the first threasholds value in opts ,

We know it’s visible if the intersectionRatio is bigger than the threshold.

Then we log the visible value and the intersectionRatio .

Next, we have the interswedtiobnObserverOptions to set the threshold of the intersection in order for it to be visible.

Then we pass them both to the IntersectionObserver constructor.

Then we call observer.observe with the target element to watch whether it’s visible or not.

Conclusion

We can compare the position of the element or use the IntersectionObserver API to check whether an element is visible or not after scrolling.