Like any kind of apps, JavaScript apps also have to be written well.
Otherwise, we run into all kinds of issues later on.
In this article, we’ll look at some tips we should follow to write JavaScript code faster and better.
Calculating the Average and Median
We can get the average by calculating the sum of the array and dividing that by the length of the array.
For instance, we can write:
const values = [2, 10, 28];
const sum = values.reduce((total, current) => current + total, 0);
const avg = sum / values.length;
We have the values
array, which we get the sum of by using reduce
.
Then we divide the returned sum by the length of values
.
To get the median, we can sort the array, then get the average of the low and high middle value from the sorted array.
For instance, we can write:
const values = [2, 10, 28];
values.sort((a, b) => a - b);
const lowMiddle = Math.floor((values.length - 1) / 2);
const highMiddle = Math.ceil((values.length - 1) / 2);
const median = (values[lowMiddle] + values[highMiddle]) / 2;
We call sort
to sort the array in ascending order by using the (a, b) => a — b
callback.
Then we get the index of the low middle value by getting the floor of value
‘s length minus 1 divided by 2.
Likewise, we get the index of the high middle value by getting the ceiling of that.
Then we get the average of both values
entries to get the median
.
JSON.Stringify
We can turn objects into a string with JSON.stringify
.
For instance, we can write:
const obj = {
foo: `1`,
bar: 2
};
const selectedProperties = ['foo'];
const str = JSON.stringify(obj, selectedProperties);
We have the obj
object which we called stringify
on with obj
and select the properties with the second argument.
Then we get:
"{"foo":1}"
as the value of str
.
We can also pass in a function:
const obj = {
foo: 1,
bar: 2
};
const selectedProperties = (key, val) => {
if (!key || key === 'foo') {
return val;
}
return;
}
const str = JSON.stringify(obj, selectedProperties);
We have a function that checks when to return val
according to the given property.
Object.defineProperties
We can use Object.defineProperty
to define a property to get more control over it.
For instance, we can write:
Object.defineProperty(obj, 'prop', {
value: '123',
enumerable: false,
writable: false,
configurable: false
});
We defined the prop
property in obj
value '123'
, and all other properties set to false
.
enumerable
means whether we can see it from Object.keys
or the for-in loop.
writable
means whether we can change the value of it.
configurable
means whether we can change the property descriptors.
Flattening Multidimensional Arrays
We can use the flat
method to flatten multidimensional arrays.
For instance, we can write:
const arr = [[1, 2],[3, 4, 5]];
const flattened = arr.flat();
Then we get [1, 2, 3, 4, 5]
for flattened
.
We can also use concat
to concatenate arrays.
For instance, we can write:
`const flattened` = [].concat.apply([], `arr`);
Also, we can use reduce
to do the same thing:
const flattened = arr.reduce((flattened, curr) => flattened.concat(curr));
The spread operator can also do the same thing:
const arr = [[1, 2],[3, 4, 5]];
const flattened = arr.reduce((flattened, curr) => [...flattened, ...curr]);
That returns the arrays merged together.
We can also use the concat
method with the spread operator:
const arr = [[1, 2],[3, 4, 5]];
const flattened = [].concat(...arr);
We spread the arr
entries into arguments of the concat
method.
Then concat
appends the entries from the arrays.
Deduplicating an Array
We can remove duplicates from an array in several ways.
We can use the filter
method to only return an array with the first instances of each entry by writing:
const deduped = [1, 1, 'b', 'b'].filter((el, i, arr) => arr.indexOf(el) === i);
We use the indexOf
method, which returns the index of the first instance of entry to check whether it’s the first instance.
Also, we can convert it to a set to remove the duplicates and put spread it back into an array:
const deduped = Array.from(new Set([1, 1, 'b', 'b']));
or:
const deduped = [...new Set([1, 1, 'b', 'b'])];
Converting an array to a set removes the duplicates. Then we use Array.from
or the spread operator to turn it back to a set.
Conclusion
We can use built-in methods and operations to calculate averages and medians.
Also, we can use them to remove duplicates.
We can also use them to flatten arrays.
JSON.stringify
can take arguments to select which properties to stringify.