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.

Categories
JavaScript Answers

How to Strip All Punctuation from a String in JavaScript Using Regex?

Sometimes, we want to strip all punctuation from a JavaScript string with a regex.

In this article, we’ll look at how to strip all punctuation from a JavaScript string with regex.

Use the String.prototype.replace Method

We can use the JavaScript string replace method to get all the parts of a string matching a regex pattern and replace them with what we want.

For instance, we can write:

const s = "This., -/ is #! an $ % ^ & * example ;: {} of a = -_ string with `~)() punctuation";
const punctuationless = s
  .replace(/[.,/#!$%^&*;:{}=-_`~()]/g, "")
  .replace(/s{2,}/g, " ");
console.log(punctuationless)

We have the s string with lots of punctuation marks we want to remove.

Next, we call replace the first time with a regex that has all the punctuation marks that we want to remove inside.

The g flag indicates we match all instances in the string that matches the given pattern.

And we replace them all with an empty string as we indicate with the 2nd argument.

Then we call replace again with a regex that matches 2 or more whitespaces.

And we replace those whitespaces with one whitespace.

Therefore, punctuationless should be ‘This is an example of a string with punctuation’ .

Conclusion

We can use the JavaScript string replace method with a regex that matches the patterns in a string that we want to replace.

So we can use it to remove punctuation by matching the punctuation and replacing them all with empty strings.