Categories
JavaScript Answers

How to Find the Max value of a Property in an Array of JavaScript Objects?

Sometimes, we’ve to find the max value of a property in an array of JavaScript objects.

In this article, we’ll look at how to find the max value of an attribute in an array of JavaScript objects.

Math.max

The Math.max method is a static method that lets us find the max value from all the arguments that are passed in.

For instance, we can write:

const array = [{
    "x": "8/11/2021",
    "y": 0.026572007
  },
  {
    "x": "8/12/2021",
    "y": 0.025057454
  },
  {
    "x": "8/13/2021",
    "y": 0.024530916
  },
  {
    "x": "8/14/2021",
    "y": 0.031004457
  }
]
const max = Math.max(...array.map(o => o.y))
console.log(max)

We call array.map to return an array with the y property values from each object in the array.

Then we use the spread operator to spread all the values into the Math.max method as arguments.

Then we get that max is 0.031004457 since this is the biggest value in the whole list.

Array.prototype.reduce

The reduce method lets us compute a result from an array of items.

We can use it to find the max value of a property in the array.

For instance, we can write:

const array = [{
    "x": "8/11/2021",
    "y": 0.026572007
  },
  {
    "x": "8/12/2021",
    "y": 0.025057454
  },
  {
    "x": "8/13/2021",
    "y": 0.024530916
  },
  {
    "x": "8/14/2021",
    "y": 0.031004457
  }
]
const maxObj = array.reduce((prev, current) => (prev.y > current.y) ? prev : current)
console.log(maxObj.y)

We call reduce with a callback that has the prev and current parameters.

prev has the result computed so far.

current has the current value of array being iterated through.

We return the object with the bigger y value in the callback.

Therefore, it should return the object with the biggest y value in the end.

And maxObj.y should be the same as max in the previous example.

Array.prototype.sort

Another way to find the max y value from the array of items is to sort the array in descending order with sort .

For example, we can write:

const array = [{
    "x": "8/11/2021",
    "y": 0.026572007
  },
  {
    "x": "8/12/2021",
    "y": 0.025057454
  },
  {
    "x": "8/13/2021",
    "y": 0.024530916
  },
  {
    "x": "8/14/2021",
    "y": 0.031004457
  }
]
const [{
  y: max
}] = array.sort((a, b) => b.y - a.y)
console.log(max)

We call array.sort with a callback that returns b.y — a.y .

a and b are objects in array being compared.

If the callback’s return value is positive, then the order of the items are switched.

Otherwise, they stay the same.

We destructure the y value from the first element on the left side and set it as the value of max .

And max has the same value as the previous examples.

Conclusion

We can find the max value of a property from an array of JavaScript objects with various array methods or the Math.max method with the spread operator.

Categories
JavaScript Answers

How to Remove the Query String from URL with JavaScript?

Sometimes, we want to remove the query string part of a URL with JavaScript.

In this article, we’ll look at how to remove the query string part of a URL string with JavaScript.

Use the String.prototype.split Method

We can use the JavaScript string split method to remove the query string from the URL string.

For instance, we can write:

const getPathFromUrl = (url) => {
  return url.split("?")[0];
}
const testURL = '/Products/List?SortDirection=dsc&Sort=price&Page=3&Page2=3&SortOrder=dsc'
console.log(getPathFromUrl(testURL))

to create the getPathFromUrl function that returns the part of the URL before the query string.

The query string always follows the question mark, so we can use split with any URL.

We call split on the url with '?' as the separator with [0] to get the part before the query string.

Therefore, in the console log, we see '/Products/List’ is logged.

Use the String.prototype.replace Method

Another way to remove the query string from the URL is to use the JavaScript string replace method.

For instance, we can write:

const getPathFromUrl = (url) => {
  return url.replace(/(?.*)|(#.*)/g, "")
}
const testURL = '/Products/List?SortDirection=dsc&Sort=price&Page=3&Page2=3&SortOrder=dsc'
console.log(getPathFromUrl(testURL))

We call replace with a regex to remove the part of the URL after the ? and also the part after the # sign with an empty string.

And so, we get the same result as we did in the previous example.

Conclusion

We can remove the query string part of a URL string in JavaScript with some string methods.

Categories
JavaScript Answers

How to Get the Week of Year of a Given Date in JavaScript?

Sometimes, we want to get the week of the year given a date.

In this article, we’ll look at how to get the week of the year of a given date with JavaScript.

Using Native JavaScript Date Methods

One way to get the week of the year of a given date is to use JavaScript date methods to compute the week of the year of a given date ourselves.

For instance, we can write:

const now = new Date(2021, 3, 1);  
const onejan = new Date(now.getFullYear(), 0, 1);  
const week = Math.ceil((((now.getTime() - onejan.getTime()) / 86400000) + onejan.getDay() + 1) / 7);  
console.log(week)

We have the now date which we want to get the year of the week from.

Then we create the onejan date with which is January 1 of the same year as now .

Then we compute the week of the year by subtracting the timestamps of now and onejan .

And then we divide that by 86400000 to get the number of days difference between the 2 dates.

Then we add the day of the week plus 1 to get the actual number of days difference.

Then we divide that by 7 to get the number of weeks difference.

And we round that number up to the nearest integer with Math.ceil .

Therefore, week is 14.

Use Moment.js

A simpler way to get the week number of the year from a given date is to use moment.js.

To use it, we write:

const now = new Date(2021, 3, 1);  
const week = moment(now).format('W')  
console.log(week)

We pass in the now date to moment to create a moment object.

Then we call format with the 'W' formatting tag to get the week of the year of now .

It rounds down, so week is 13.

Conclusion

We can use JavaScript date methods or use moment.js to get the week of the year.

Categories
JavaScript Answers

How to Return the Index of the Greatest Value in a JavaScript Array?

Sometimes, we want to return the index of the greatest value in a JavaScript array.

In this article, we’ll look at how to return the index of the greater value in a JavaScript array.

Use the Array.prototype.indexOf and Math.max Methods

We can find the index of the greatest value in a JavaScript array with the Math.max and the array’s indexOf method.

For instance, we can write:

const arr = [0, 21, 22, 7];
const index = arr.indexOf(Math.max(...arr));
console.log(index)

We call Math.max with the elements of arr in as arguments by spreading arr into the Math.max method.

This returns the greatest element in arr .

And then we can call arr.indexOf on the greatest element of arr .

And so index is 2, which is the index of value 22 in arr .

Use the Array.prototype.reduce Method

Another way to get the index of the greatest element in an array is to use the JavaScript array’s reduce method.

To use it, we write:

const arr = [0, 21, 22, 7];
const index = arr.reduce((iMax, x, i, arr) => x > arr[iMax] ? i : iMax, 0);
console.log(index)

We call reduce on arr with a callback that has the iMax parameter, which is the index of the greatest value of arr so far.

x is the entry of arr being iterated through.

i is the index of x .

arr is the arr array itself.

We return the index of the greatest element by checking if x is bigger than the current element being recorded as the largest so bar, which is arr[iMax] .

If x is bigger than arr[iMax] , we return i .

Otherwise, we return iMax .

0 is the initial value of the index of the greatest element of arr .

And so index is 2 as we saw in the previous example.

Conclusion

We can use the Math.max and Array.prototype.indexOf or Array.prototype.reduce methods to get the index of the greatest elements in a JavaScript array.

Categories
JavaScript Answers

How to Get HTML Elements with Multiple Classes with JavaScript?

Sometimes, we want to get multiple elements with multiple classes with JavaScript.

In this article, we’ll look at how to get HTML elements with multiple classes with JavaScript.

Get HTML Elements with Both Classes

To get HTML elements with both classes, we can use the getElementsByClassName or querySelectorAll methods.

For instance, if we have the following HTML:

<div class='class1'>  
  foo  
</div>  
<div class='class2'>  
  bar  
</div>  
<div class='class1 class2'>  
  baz  
</div>

Then we can get the div with text ‘baz’ by writing:

const list1 = document.getElementsByClassName("class1 class2");  
const list2 = document.querySelectorAll(".class1.class2");  
console.log(list1)  
console.log(list2)

We call getElementsByClassName with 'class1 class2' to get the div with both class1 and class2 present.

Likewise, we can do the same with querySelectorAll by using the “.class1.class2” CSS selector.

Then list1 is the HTMLCollection with the 3rd div.

And list2 is the NodeList with the 3rd div.

Get HTML Elements with At Least One Class

We can get HTML elements with at least one class by using the querySelector method.

For instance, if we have the following HTML:

<div class='class1'>  
  foo  
</div>  
<div class='class2'>  
  bar  
</div>  
<div class='class1 class2'>  
  baz  
</div>

Then we can write:

const list = document.querySelectorAll(".class1,.class2");  
console.log(list)

We use “.class1,.class2” with querySelectorAll to get elements with class1 or class2 or both as the class.

And so list is a NodeList with all 3 elements.

Get HTML Elements with One Class But Not Both

We can also use querySelector to get HTML elements with one class but not both.

For instance, if we have the following HTML:

<div class='class1'>  
  foo  
</div>  
<div class='class2'>  
  bar  
</div>  
<div class='class1 class2'>  
  baz  
</div>

Then we write:

const list = document.querySelectorAll(".class1:not(.class2),.class2:not(.class1)");  
console.log(list)

We use the :not pseudo-selector to exclude class2 with class1 and class1 with class2 .

So list is a NodeList with the first 2 divs.

Get HTML Elements with None of the Classes or One Class Only

To get all the elements with none of the classes or only one of the classes applied to it, we can use the :not pseudo-selector again.

For instance, if we have the following HTML:

<div class='class1'>  
  foo  
</div>  
<div class='class2'>  
  bar  
</div>  
<div class='class1 class2'>  
  baz  
</div>

Then we can write:

const list = document.querySelectorAll(":not(.class1),:not(.class2)");  
console.log(list)

And we get all the elements in the page but the div with text baz.

Get HTML Elements with None of the Classes

To get the HTML elements with none of the classes, we can use the :not pseudo-selector again.

For instance, if we have the following HTML:

<div class='class1'>  
  foo  
</div>  
<div class='class2'>  
  bar  
</div>  
<div class='class1 class2'>  
  baz  
</div>

Then we can write:

const list = document.querySelectorAll(":not(.class1):not(.class2)");  
console.log(list)

to select anything but the divs with class1 or class2 .

Conclusion

We can use querySelector to select element with any combinations of the classes applied to an element we want.