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.

Categories
JavaScript Answers

How to Append a Property to a JavaScript Object?

Oftentimes, we want to append new properties to a JavaScript object in our code.

In this article, we’ll look at how to append a property to a JavaScript object.

Use the Object.assign Method

One way to append a property to a JavaScript object is to use the Object.assign method.

For instance, we can write:

const obj = {  
  foo: 1,  
  bar: 2  
}  
const newObj = Object.assign({}, obj, {  
  baz: 3  
})  
console.log(newObj)

We have an obj that we want to to add the baz property into it.

To do that, we call Object.assign with an empty object, obj and an object with the baz property.

Then all the properties from the objects in the 2nd and 3rd arguments are put into the empty object and returned.

Therefore, newObj is:

{  
  "foo": 1,  
  "bar": 2,  
  "baz": 3  
}

Use the Spread Operator

Another way to add a property into an object is to use the spread operator.

For instance, we can write:

const obj = {  
  foo: 1,  
  bar: 2  
}  
const newObj = {  
  ...obj,  
  baz: 3  
}  
console.log(newObj)

We spread the properties of obj into newObj .

And then we put the baz property after that.

Therefore, newObj is:

{  
  "foo": 1,  
  "bar": 2,  
  "baz": 3  
}

Conclusion

We can use the Object.assign method or the spread operator to append a property to an object.

Categories
JavaScript Answers

How to Build a Tree Array from Flat Array in JavaScript?

Sometimes, we want to build a tree array from a flattened array in JavaScript.

In this article, we’ll look at how to build a tree array from a flattened array with JavaScript.

Use JavaScript Array Methods and Recursion

We can easily build a tree array from a flattened array with various array methods and recursion.

For instance, we can write:

const comments = [{
  id: 1,
  parentId: null
}, {
  id: 2,
  parentId: 1
}, {
  id: 3,
  parentId: 1
}, {
  id: 4,
  parentId: 2
}, {
  id: 5,
  parentId: 4
}];

const nest = (items, id = null, link = 'parentId') =>
  items
  .filter(item => item[link] === id)
  .map(item => ({
    ...item,
    children: nest(items, item.id)
  }));

console.log(nest(comments))

We have the comments array with the id and parentId properties where the parentId the id of the parent comment.

Then we create the nest function that takes the items array, id and link .

id is the value of parentId .

And link has the property name of the parent ID.

In the function, we call filter to get the child comments with the given ID.

Then call map to map the item with the children array property with the child comments that we get from the nest method.

Therefore, the console log should log:

[
  {
    "id": 1,
    "parentId": null,
    "children": [
      {
        "id": 2,
        "parentId": 1,
        "children": [
          {
            "id": 4,
            "parentId": 2,
            "children": [
              {
                "id": 5,
                "parentId": 4,
                "children": []
              }
            ]
          }
        ]
      },
      {
        "id": 3,
        "parentId": 1,
        "children": []
      }
    ]
  }
]

Conclusion

We can unflatten an array and return a tree array with some array methods and recursion with JavaScript.