Categories
JavaScript Answers

How to filter strings in array based on content with JavaScript?

To filter strings in array based on content with JavaScript, we use the filter method.

For instance, we write

const PATTERN = /bedroom/;
const filtered = myArray.filter((str) => {
  return PATTERN.test(str);
});

to call myArray.filter with a callback that calls PATTERN.test to check if str matches the PATTERN regex pattern.

An array with the strings that matches PATTERN is returned.

Categories
JavaScript Answers

How to access first element of JSON object array with JavaScript?

To access first element of JSON object array with JavaScript, we use index 0.

For instance, we write

const req = { events: [{ event: "inbound", ts: 1426249238 }] };
console.log(req.events[0]);

to get the req.events array property and get its first item with index 0 in the square brackets.

Categories
JavaScript Answers

How to check if an array item is set in JavaScript?

To check if an array item is set in JavaScript, we use the in operator.

For instance, we write

const assocPagine = {
  home: 0,
  about: 1,
  work: 2,
};

if ("work" in assocPagine) {
  // ...
}

to check if the work property is in the assocPagine object as a property in the object itself or as an inherited property.

Categories
JavaScript Answers

How to replace a string in a JavaScript array?

To replace a string in a JavaScript array, we use the array map and string replaace methods.

For instance, we write

const resultArr = arr.map((x) => {
  return x.replace(/,/g, "");
});

to call arr.map with a callback that returns a new string that replace commas in x with empty strings with replace.

A new array with the replacements done is returned.

Categories
JavaScript Answers

How to count the number of true values in an array of boolean values with JavaScript?

To count the number of true values in an array of boolean values with JavaScript, we call the filter method.

For instance, we write

const arr = [true, false, true, false, true];
const count = arr.filter(Boolean).length;

to call arr.filter with Boolean to return an array with the truthy values in arr in a new array.

Then we get the count of that with the length property.