Categories
JavaScript Answers

How to get the second to last item of an array with JavaScript?

To get the second to last item of an array with JavaScript, we use the length subtract by 2 index.

For instance, we write

const pgUrl = array[array.length - 2];

to get the 2nd last item in array with index array.length - 2.

Categories
JavaScript Answers

How to split string with white space with JavaScript?

To split string with white space with JavaScript, we use the split method.

For instance, we write

const str = "my car is green";
const stringArray = str.split(/(\s+)/);

to call str.split with a regex that matches whitespaces to split the str string by the whitespaces and return an array with the split substrings.

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.