Categories
JavaScript Answers

How to get a list of associative array keys with JavaScript?

To get a list of associative array keys with JavaScript, we call the Object.keys method.

For instance, we write

const dictionary = {
  cats: [1, 2, 37, 38, 40, 32, 33, 35, 39, 36],
  dogs: [4, 5, 6, 3, 2],
};

const keys = Object.keys(dictionary);
console.log(keys);

to call Object.keys with dictionary to return a list of key strings from the dictionary object.

Categories
JavaScript Answers

How to do map and filter an array at the same time with JavaScript?

To map and filter an array at the same time with JavaScript, we use the flatMap method.

For instance, we write

const names = options.flatMap((o) => (o.assigned ? [o.name] : []));

to call options.flatMap with a callback that checks if o.assigned is set.

If it is, then we array with o.name inside.

Otherwise, we return an empty array.

And we use flatMap to combine them into one flattened array.

Categories
JavaScript Answers

How to check if a string contains text from an array of substrings in JavaScript?

To check if a string contains text from an array of substrings in JavaScript, we can use the some and includes method.

For instance, we write

if (substrings.some((v) => str.includes(v))) {
  // ...
}

to call some on the substrings array with a callback that calls str.includes with the v entry being looped through in substrings to check if v is in the str string.

If any value v is in str, then some returns true.

Categories
JavaScript Answers

How to split a string into segments of n characters with JavaScript?

To split a string into segments of n characters with JavaScript, we call the match method.

For instance, we write

const str = "abcdefghijkl";
console.log(str.match(/.{1,3}/g));

to call str.match with a regex the matches groups of 1 to 3 characters in the str array.

Categories
JavaScript Answers

How to create an empty typed container array with TypeScript?

To create an empty typed container array with TypeScript, we can declare the type explicitly.

For instance, we write

const arr: Criminal[] = [];

to declare the arr array with the Criminal type.