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.

Categories
JavaScript Answers

How to convert JavaScript array to CSV?

To convert JavaScript array to CSV, we clal the map and join methods.

For instance, we write

const testArray = [
  ["name1", 2, 3],
  ["name2", 4, 5],
  ["name3", 6, 7],
  ["name4", 8, 9],
  ["name5", 10, 11],
];
const csv = testArray.map((row) => row.join(",")).join("\n");

to call testArray.map with a callback that joins the array entries into a comma separated string with row.join(",").

And then we combine the row strings into a CSV string by calling join with '\n'.

Categories
JavaScript Answers

How to filter array of objects based on another array in JavaScript?

To filter array of objects based on another array in JavaScript, we call the includes method.

For instance, we write

const filtered = people.filter((person) => idFilter.includes(person.id));

to call people.filter with a callback that calls idFilter.includes to check if person.id is included in the idFilter array.

Then an array with the objects that have id property included in the idFilter array is included.