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.
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.
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.
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.
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.
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.