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.

Categories
JavaScript Answers

How to check if a key exists in a JavaScript object?

To check if a key exists in a JavaScript object, we use the hasOwnProperty method.

For instance, we write

const obj = { key: undefined };
console.log(obj.hasOwnProperty("key"));

to call obj.hasOwnProperty to check if the 'key' property is in the obj object itself.

Categories
JavaScript Answers

How to insert an item into an array at a specific index with JavaScript?

To insert an item into an array at a specific index with JavaScript, we can assign the value directly.

For instance, we write

const arr = [];
arr[0] = "Jane";
arr[1] = "Alex";
arr[2] = "Bob";

to set the entry at index 0 to 'Jane'.

We set the entry at index 1 to 'Alex'.

And we set the entry at index 2 to 'Bob'.

Categories
JavaScript Answers

How to check if an array includes a value in JavaScript?

To check if an array includes a value in JavaScript, we use the includes method.

For instance, we write

console.log(["joe", "jane", "mary"].includes("jane"));

to call includes to check if 'jane' is in the ["joe", "jane", "mary"] array.

Since 'jane' is in the array, true is returned.