Categories
JavaScript Answers

How to empty an array in JavaScript?

To empty an array in JavaScript, we set it to an empty array.

For instance, we write

let arr1 = ["a", "b", "c", "d", "e", "f"];
arr1 = [];

to assign the arr1 array to an empty array to empty the array.

Categories
JavaScript Answers

How to get all unique values in a JavaScript array?

To get all unique values in a JavaScript array, we can convert it to a set and back.

For instance, we write

const myArray = ["a", 1, "a", 2, "1"];
const unique = [...new Set(myArray)];
console.log(unique);

to convert the myArray array to a set with the Set constructor.

Then we convert the set back to an array without duplicate values with the spread operator.

Categories
JavaScript Answers

How to append something to an array with JavaScript?

To append something to an array with JavaScript, we call the array push method.

For instance, we write

const arr = ["Hi", "Hello", "Bonjour"];
arr.push("Hola");

console.log(arr);

to call arr.push to append 'Hola' as the last entry of arr in place.

Categories
JavaScript Answers

How to loop through an array in JavaScript?

To loop through an array in JavaScript, we use a for-of loop.

For instance, we write

const colors = ["red", "green", "blue"];
for (const color of colors) {
  console.log(color);
}

to loop through the colors array with a for-of loop.

And we get the value being looped through with color.

Categories
JavaScript Answers

How to sort array of objects by string property value with JavaScript?

To sort array of objects by string property value with JavaScript, we use the sort method.

For instance, we write

const compare = (a, b) => {
  if (a.lastName < b.lastName) {
    return -1;
  }
  if (a.lastName > b.lastName) {
    return 1;
  }
  return 0;
};

const sorted = objs.sort(compare);

to call sort with the compare function to return a number determining the order of the items.

We return -1 if a.lastName is before b.lastName.

We return 1 if a.lastName is after b.lastName.

And we return 0 otherwise.

An array with the values sorted by the lastName property of each object is returned.