Categories
JavaScript Answers

How to check if an array is empty or exists with JavaScript?

To check if an array is empty or exists with JavaScript, we use the Array.isArray method and the array’s length property.

For instance, we write

if (Array.isArray(array) && array.length) {
  // ...
}

to check if array is an array with Array.isArray.

And then we use array.length to check if it’s bigger than 0 to check if it’s filled with content.

Categories
JavaScript Answers

How to replace item in array with JavaScript?

To replace item in array with JavaScript, we can assign a new value directly.

For instance, we write

const items = [523, 3452, 334, 31, 57];

const index = items.indexOf(3452);

if (index !== -1) {
  items[index] = 1010;
}

to call items.indexOf to get the index of 3452.

Then we check if index isn’t -1.

If it’s not, then the item exists and we can assign a new value to it with

items[index] = 1010;
Categories
JavaScript Answers

How to get all non-unique values in an array with JavaScript?

To get all non-unique values in an array with JavaScript, we call the filter and indexOf methods.

For instance, we write

const noDups = [1, 2, 2, 4, 3, 4].filter((e, i, a) => a.indexOf(e) !== i);

to call filter with a callback that checks if a.indexOf returns an index that’s different from i.

If this is true, that means there’s a duplicate of e since indexOf returns the first index of e.

Categories
JavaScript Answers

How to check in JavaScript if a value exists at a certain array index?

To check in JavaScript if a value exists at a certain array index, we use check if the array item at the index is undefined or not.

For instance, we write

if (arrayName[index]) {
  //...
}

to get the item in arrayName at index.

If it’s not undefined, then the value exists.

Categories
JavaScript Answers

How to create an array with same element repeated multiple times with JavaScript?

To create an array with same element repeated multiple times with JavaScript, we call the fill method.

For instance, we write

const arr = Array(15).fill(2);

to create an empty array with 15 slots with Array.

And then we call fill to fill all the slots with 2’s.