Categories
TypeScript Answers

How to take object out of array based on attribute value with TypeScript?

To take object out of array based on attribute value with TypeScript, we use the find method.

For instance, we write

const array = [
  { id: 1, value: "itemname" },
  { id: 2, value: "itemname" },
];

const item1 = array.find((i) => i.id === 1);

to call array.find with a callback that finds the first object in array that has id equal to 1.

Categories
JavaScript Answers

How to sum up an array in JavaScript?

To sum up an array in JavaScript, we use the reduce method.

For instance, we write

const sum = array.reduce((pv, cv) => pv + cv, 0);

to call array.reduce with a callback that returns the sum between partial sum pv and the current value cv.

We set the initial sum value to 0 with the 2nd argument.

Categories
JavaScript Answers

How to dynamically create nested objects using object names given by an array with JavaScript?

To dynamically create nested objects using object names given by an array with JavaScript, we use the reduce method.

For instance, we write

const set = (obj, path, val) => {
  const keys = path.split(".");
  const lastKey = keys.pop();
  const lastObj = keys.reduce((obj, key) => (obj[key] = obj[key] ?? {}), obj);
  lastObj[lastKey] = val;
};
const obj = { a: { prop: { that: "exists" } } };
set(obj, "a.very.deep.prop", "value");

to define the set function.

In it, we call split on the path to split the object path.

And then we get the last key with pop.

Then we call keys.reduce with a callback that returns sets the key property to an empty object if it doesn’t exist.

And then we set the lastKey of the nested property to val.

Categories
JavaScript Answers

How to remove key and value from hash in JavaScript?

To remove key and value from hash in JavaScript, we use the delete operator.

For instance, we write

delete myHash['key2']

to remove the property with key key2 from the myHash object with the delete operator.

Categories
JavaScript Answers

How to join an array by a comma and a space with JavaScript?

To join an array by a comma and a space with JavaScript, we use the join method.

For instance, we write

const myArray = [
  "css",
  "html",
  "xhtml",
  "html5",
  "css3",
  "javascript",
  "jquery",
  "lesscss",
  "arrays",
  "wordpress",
  "facebook",
  "fbml",
  "table",
  ".htaccess",
  "php",
  "c",
  ".net",
  "c#",
  "java",
];
const myString = myArray.join(", ");

to call myArray.join with ', ' to combine the strings in myArray into a string with the entries separated by ', '.