Categories
JavaScript Answers

How to Detect Arrow Key Presses in JavaScript?

Sometimes we need to detect the arrow key presses in our JavaScript web apps.

In this article, we’ll look at how to detect arrow key presses in JavaScript.

Use the keyCode Property

We can listen to the keydown event and get the keyCode property from the event object.

For instance, we can write:

document.onkeydown = (e) => {  
  e = e || window.event;  
  if (e.keyCode === 38) {  
    console.log('up arrow pressed')  
  } else if (e.keyCode === 40) {  
    console.log('down arrow pressed')  
  } else if (e.keyCode === 37) {  
    console.log('left arrow pressed')  
  } else if (e.keyCode === 39) {  
    console.log('right arrow pressed')  
  }  
}

to assign the keydown event handler function to the document.onkeydown property.

This lets us listen to the keydown event on the HTML document.

Then we can get the keyCode property from the e event object to see which key is pressed.

38 is the code for the up arrow.

40 is the code for the down arrow.

37 is the code for the left arrow.

And 39 is the code for the right arrow.

Also, we can use the addEventListener method to add the keydown event listener:

document.addEventListener('keydown', (e) => {  
  e = e || window.event;  
  if (e.keyCode === 38) {  
    console.log('up arrow pressed')  
  } else if (e.keyCode === 40) {  
    console.log('down arrow pressed')  
  } else if (e.keyCode === 37) {  
    console.log('left arrow pressed')  
  } else if (e.keyCode === 39) {  
    console.log('right arrow pressed')  
  }  
})

Use the key Property

Also, we can use the key property from the event object to the key that’s pressed as a string instead of a number.

For instance, we can write:

document.onkeydown = (e) => {  
  e = e || window.event;  
  if (e.key === 'ArrowUp') {  
    console.log('up arrow pressed')  
  } else if (e.key === 'ArrowDown') {  
    console.log('down arrow pressed')  
  } else if (e.key === 'ArrowLeft') {  
    console.log('left arrow pressed')  
  } else if (e.key === 'ArrowRight') {  
    console.log('right arrow pressed')  
  }  
}

We compare the key property value against the string names for the keys.

Also, we can use addEventListener method to add the key down listener by writing:

document.addEventListener('keydown', (e) => {  
  e = e || window.event;  
  if (e.key === 'ArrowUp') {  
    console.log('up arrow pressed')  
  } else if (e.key === 'ArrowDown') {  
    console.log('down arrow pressed')  
  } else if (e.key === 'ArrowLeft') {  
    console.log('left arrow pressed')  
  } else if (e.key === 'ArrowRight') {  
    console.log('right arrow pressed')  
  }  
})

Conclusion

We can detect arrow key presses by listening to the keydown event.

And in the event listener, we can either check the key or keydown properties of the event object to see which key is pressed.

Categories
JavaScript Answers

How to Remove the Last Item from a JavaScript Array?

Removing a last item from the JavaScript array is something that we’ve to do sometimes with our code.

In this article, we’ll look at how to remove the last item from a JavaScript array.

Array.prototype.splice

We can use the JavaScript array’s splice method to remove the last item from the array.

For instance, we can write:

const array = [1, 2, 3]
array.splice(-1, 1)
console.log(array)

We call splice with -1 to remove the last item from the array.

And 1 specifies that remove one item.

Then array is [1, 2] .

Array.prototype.pop

We can call the pop method to remove the last item from the array.

It returns the item that’s been removed.

To use it, we can write:

const array = [1, 2, 3]
const popped = array.pop()
console.log(popped, array)

We call pop on array to remove the last item from array .

And we assigned the removed item to popped .

So popped is 3.

And array is [1, 2] .

Array.prototype.slice

Another array method we can use to remove the last item from an array is the slice method.

It returns an array with the start and end index.

For instance, we can write:

const array = [1, 2, 3]
const newArr = array.slice(0, -1);
console.log(newArr)

We call slice with the start and end index to return an array from the start index to the end index.

The item at the end index isn’t included, but the one in the start is included.

The number -1 means the index of the last item in the array.

Therefore, we get:

[1, 2]

as the value of newArr .

Array.prototype.filter

We can use the array filter method to return an array with items that meet the given condition.

Therefore, we can check if the item is in the last index of the array.

For instance, we can write:

const array = [1, 2, 3]
const newArr = array.filter((element, index) => index < array.length - 1);
console.log(newArr)

We pass in a callback to the filter method that returns index < array.length — 1 to return all the items with index less than array.length — 1 .

Therefore, we’ll get the same result for newArr as the previous example.

Conclusion

We can use JavaScript array methods to remove the last item from an array.

Categories
JavaScript Answers

How to Get Distinct Values From an Array of Objects in JavaScript?

Sometimes we may want to get distinct values from an array of objects in our JavaScript code.

In this article, we’ll look at how to get distinct values from an array of objects in JavaScript.

Extracting Values with Array Methods

One way to get distinct values from an array of objects in JavaScript is to use native array methods.

For instance, we can write:

const array = [{
    "name": "jane",
    "age": 17
  },
  {
    "name": "joe",
    "age": 17
  },
  {
    "name": "bob",
    "age": 35
  }
];
const uniques = array.map(item => item.age)
  .filter((value, index, self) => self.indexOf(value) === index)
console.log(uniques)

to call the map and filter to return unique values of the age property from all the items in the array.

We call map to return an array with all the age values.

Then we use filter to return an array with distinct values of the age value array returned from map .

The callback we pass into filter has the value , index and self parameters.

value has the value being iterated through.

index has the index of the value .

And self is the array itself.

We can check if it’s the first instance of a given value with self.indexOf(value) === index .

indexOf returns the index of the first instance of value in the array.

So we can use that return an array that only has the first instance of a given element.

Therefore uniques is [17, 35] .

We can replace the filter call by putting the age value array in a set and then spreading that back into an array:

const array = [{
    "name": "jane",
    "age": 17
  },
  {
    "name": "joe",
    "age": 17
  },
  {
    "name": "bob",
    "age": 35
  }
];
const uniques = [...new Set(array.map(item => item.age))]
console.log(uniques)

And uniques has the same value as the previous example.

The spreading can be replaced with the Array.from method:

const array = [{
    "name": "jane",
    "age": 17
  },
  {
    "name": "joe",
    "age": 17
  },
  {
    "name": "bob",
    "age": 35
  }
];
const uniques = Array.from(new Set(array.map(item => item.age)))
console.log(uniques)

since Array.from works with any iterable objects, including sets, to convert them into an array.

Lodash

Lodash has the uniq method to return unique values from an array of objects.

So we can use it by writing;

const array = [{
    "name": "jane",
    "age": 17
  },
  {
    "name": "joe",
    "age": 17
  },
  {
    "name": "bob",
    "age": 35
  }
];
const uniques = _.uniq(_.map(array, 'age'));
console.log(uniques)

We call map to return an array of age values from array .

And then we call uniq on the returned array to get the unique values from that returned array.

So we get the same result for uniques as the other examples.

Conclusion

We can use native JavaScript array methods or Lodash to extract distinct values from a property from an array of objects.

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.