Categories
JavaScript Answers

How to convert object array to hash map, indexed by an attribute value of the object with JavaScript?

To convert object array to hash map, indexed by an attribute value of the object with JavaScript, we use the Object.entries and Object.fromEntries methods.

For instance, we write

const array = [
  { key: "a", value: "b", redundant: "aaa" },
  { key: "x", value: "y", redundant: "zzz" },
];

const hash = Object.fromEntries(array.map((e) => [e.key, e.value]));

console.log(hash);

to call array.map to map the entries to an array of key-value pair arrays with the callback.

Then we call Object.fromEntries to convert the array to an object with the key as the property key and the values as the property values.

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.