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.

Categories
JavaScript Answers

How to use the reduce function to return a JavaScript array?

To use the reduce function to return a JavaScript array, we return the array in the reduce callback.

For instance, we write

const store = [0, 1, 2, 3, 4];

const stored = store.reduce((pV, cV, cI) => {
  return [...pV, cV];
}, []);

console.log(stored);

to call store.reduce with a callback that destructures the pV array we get from the reduce process.

And then we spread the entries from there and the put cV at the end of it and return the array.

Categories
JavaScript Answers

How to loop through array backwards with forEach with JavaScript?

To loop through array backwards with forEach with JavaScript, we call reverse before calling forEach.

For instance, we write

const arr = [1, 2, 3];

arr
  .slice()
  .reverse()
  .forEach((x) => console.log(x));

to call arr.slice to return a copied version of the arr array.

And then we call reverse to reverse the copied array.

Then we call forEach with a callback to log each entry x being looped through.