Arrays are something all of us come across every day. Today I'll share my picks for 3 of the most uncommonly used Array methods.
isArray
In JavaScript, we have to infer the data type of variables way too often, even more often in nested Objects. One of the ways most JavaScript developers do it (including myself) is to check the length property
const data = { ... }
(data?.arrayKey && data.arrayKey.length)
Although this works, what if I told you there is even a better way to do this?
The Array.isArray(param: any) call checks if the passed value is indeed an array or not and returns a boolean value.
Array.isArray([]);
Array.isArray(new Array(22));
Array.isArray(0)
Array.isArray({});
Array.isArray(null);
Array.isArray(undefined);
For the next two, let's consider a situation
You have to rate some students based on a test as follows
- failed: if all answers were wrong
- passed: if some answers were correct
- excellent: if all answers were correct
some
The Array.some() methods run the provided function on each item of the array and return true, if the provided function returns true for any of them, otherwise false.
So in our scenarios, we can apply Array.some() for the second use case.
function isCorrectAnswer(answer) {
}
const answers = [{ ... }]
const didStudentPass = answers.some(isCorrectAnswer)
every
The Array.every() methods run the provided function on each item of the array and return true, if the provided function returns true for all of them, otherwise false.
Array.every() seems like a perfect fit for the other two scenarios.
function isCorrectAnswer(answer) {
}
function isInCorrectAnswer(answer) {
}
const answers = [{ ... }]
const didStudentFail = answers.every(isInCorrectAnswer)
const didStudentExcel = answers.every(isCorrectAnswer)
That's it for now. I hope you find this article helpful! Should you have any feedback or questions, please feel free to put them in the comments below, I would love to hear and work on them.
For more such content, please follow me
Until next time
