Categories
JavaScript Answers

How to Get the Nth Occurrence of a Substring in a String with JavaScript?

We can get the nth occurrence of a substring in a string with some JavaScript string methods.

For instance, we can write:

const string = "XYZ 123 ABC 456 ABC 789 ABC";

const getPosition = (string, subString, index) => {
  return string.split(subString, index).join(subString).length;
}

console.log(
  getPosition(string, 'ABC', 2)
)

We call split with substring and index to split the string with substring as the delimited and limit the number of splits to index .

Then we join back the string with substring with join to join the string back together.

And then we get the length of the joined string to get the index of the index th occurrence of a string.

Therefore, the console log should log 16 since that’s the start of the 2nd occurrence of 'ABC' .

Categories
JavaScript Answers

How to Generate Unique Random Numbers Between 1 and 100 with JavaScript?

We can use the while loop to generate a given number of random numbers and put them in an array.

For instance, we can write:

const arr = [];
while (arr.length < 8) {
  const r = Math.floor(Math.random() * 100) + 1;
  if (arr.indexOf(r) === -1) {
    arr.push(r);
  }
}
console.log(arr);

We create the arr array which we store the randomly generated numbers in.

Then we have the while loop that checks if arr.length is less than a given number.

Then we generate the number with Math.random with Math.floor if the while loop condition is met.

Since Math.random only generates numbers between 0 and 1, we’ve to multiply the returned result by 100, round it down with Math.floor and add 1 to it.

If the number isn’t already in arr as returned by indexOf , then we call push to add it to arr .

Generate Unique Random Numbers Between 1 and 100 with JavaScript with Sets

We can also use a set instead so we don’t have to check if a number is already in the set.

If it’s already in the set, then it won’t be added again.

For instance, we can write:

const nums = new Set();
while (nums.size !== 8) {
  nums.add(Math.floor(Math.random() * 100) + 1);
}

console.log([...nums]);

We call add to add items to the set.

And we spread the nums set into an array to convert it back to an array.

Categories
JavaScript Answers

Check if a DOM Element is a Child of a Parent with JavaScript?

We can use the contains method to check if a DOM element is a child of a parent.

For instance, if we have the following HTML:

<div id='parent'>
  <div id='child'>
    hello
  </div>
</div>

Then we can do the check by writing:

const contains = (parent, child) => {
  return parent !== child && parent.contains(child);
}

const parentEl = document.querySelector('#parent'),
  childEl = document.querySelector('#child')

if (contains(parentEl, childEl)) {
  console.log('is parent')
}

We have the contains function that gets the parent and child elements.

And we do the check by checking if parent isn’t the same as child and also use the contains method to see if child is inside parent .

We then call contains to see if parentEl is the parent of childEl after getting those elements with document.querySelector .

Categories
JavaScript Answers

How to Count Duplicate Values in an Array in JavaScript?

Count Duplicate Values in an Array in JavaScript with forEach

We can use the JavaScript array forEach method to loop through the array we want to count the duplicates for and add the count of each item into an object.

For instance, we can write:

const arr = ["a", "b", "c", "d", "e", "a", "b", "c", "f", "g", "h", "h", "h", "e", "a"]
const counts = {};
arr.forEach((x) => {
  counts[x] = (counts[x] || 0) + 1;
});
console.log(counts)

We call forEach on arr with a callback that puts the array item x as a property of count .

Then we update counts[x] as the item x is being found from iteration.

If count[x] isn’t set yet, then 0 is set as the value of count[x] .

Then we get that counts is:

{
  "a": 3,
  "b": 2,
  "c": 2,
  "d": 1,
  "e": 2,
  "f": 1,
  "g": 1,
  "h": 3
}

where the keys are the arr items and the values are the counts of those items.

Categories
JavaScript Answers

How to Make a Div Visible and Invisible with JavaScript?

One way to make a div visible or invisible is with the visibility property.

For instance, if we have a div:

<div>  
  hello world  
</div>

Then we can make it visible with:

const div = document.querySelector('div')  
div.style.visibility = 'visible'

And we can make it invisible with:

const div = document.querySelector('div')  
div.style.visibility = 'hidden'

Make a Div Visible and Invisible with JavaScript with the display Property

Another way to make a div visible or invisible is with the display property.

For instance, if we have a div:

<div>  
  hello world  
</div>

Then we can make it visible with:

const div = document.querySelector('div')  
div.style.display = 'inline';

to make the div display inline with other elements.

And we can write:

const div = document.querySelector('div')  
div.style.display = 'block';

to make it display in its own row.

And we can make it invisible with:

const div = document.querySelector('div')  
div.style.display = 'none';