Categories
JavaScript Answers

How to convert Map to JSON object in JavaScript?

To convert Map to JSON object in JavaScript, we use the Object.fromEntries method.

For instance, we write

const map1 = new Map([
  ["foo", "bar"],
  ["baz", 42],
]);

const obj = Object.fromEntries(map1);

to create a map with the Map constructor.

Then we call Object.fromEntries with map1 to convert it to an array of key-value pair arrays.

Categories
JavaScript Answers

How to check whether multiple values exist within a JavaScript array?

To check whether multiple values exist within a JavaScript array, we use the every and includes methods.

For instance, we write

const success = arrayA.every((val) => arrayB.includes(val));

to call arrayA.every with a callback that checks if every val in arrayA is in “arrayBwithincludes`.

If the condition is met for all elements in arrayA, then true is return.

Categories
JavaScript Answers

How to loop through a set of elements in JavaScript?

To loop through a set of elements in JavaScript, we use a for-of loop.

For instance, we write

const list = [
  { a: 1, b: 2 },
  { a: 3, b: 5 },
  { a: 8, b: 2 },
  { a: 4, b: 1 },
  { a: 0, b: 8 },
];

for (const item of list) {
  console.log(item);
}

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

Then we get the item being looped through and log it.

Categories
JavaScript Answers

How to get array element fulfilling a condition with JavaScript?

To get array element fulfilling a condition with JavaScript, we call the filter method.

For instance, we write

const isGreaterThanFive = (x) => {
  return x > 5;
};

const filtered = [1, 10, 4, 6].filter(isGreaterThanFive);

to call [1, 10, 4, 6].filter with isGreaterThanFive to return an array with the entries that are greater than 5 in the [1, 10, 4, 6] array.

Categories
JavaScript Answers

How to sort a JavaScript array with arrays in it by string?

To sort a JavaScript array with arrays in it by string, we call the sort method.

For instance, we write

const comparator = (a, b) => {
  if (a[1] < b[1]) return -1;
  if (a[1] > b[1]) return 1;
  return 0;
};

const myArray = [
  [1, "alfred", "..."],
  [23, "berta", "..."],
  [2, "zimmermann", "..."],
  [4, "albert", "..."],
];

const sortedMyArray = myArray.sort(comparator);

to call myArray.sort with the comparator function to sort the array in ascending order by the 2nd entry of each array.

We do the comparison with the comparison operators and return -1 if a[1] comes before b[1].

And we return 1 when a[1] comes after b[1] to sort in ascending order.