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.

Categories
JavaScript Answers

How to match string against the array of regular expressions with JavaScript?

To match string against the array of regular expressions with JavaScript, we use the some method.

For instance, we write

const regexList = [/apple/, /pear/];
const text = "banana pear";
const isMatch = regexList.some((rx) => rx.test(text));

to call regexList.some with a callback that calls rx.test with text to check if text matches any of the regexes in regexList.

Categories
JavaScript Answers

How to compare 2 arrays which returns difference with JavaScript?

To compare 2 arrays which returns difference with JavaScript, we use the filter and indexOf methods.

For instance, we write

const diff = (a, b) => b.filter((i) => a.indexOf(i) === -1);

to call b.filter with a callback that calls a.indexOf with i to see if i isn’t included in a by checking if indexOf returns -1.

An array with the items in b that’s not in a is returned.

Categories
JavaScript Answers

How to sort array and get unique entries with JavaScript?

To sort array and get unique entries with JavaScript, we use a set.

For instance, we write

const myData = ["237", "124", "255", "124", "366", "255"];
const uniqueAndSorted = [...new Set(myData)].sort();

to convert the myData array to a set with the Set constructor to remove the duplicates.

Then we spread the set elements into an array with the spread operator.

Finally, we sort the array without the duplicates with sort.