Take an array with a string as an element and return an array with the shortest and longest strings removed.
This was a algorithm question I went through and failed for two days so I took a look into the reference code and decided understand the code and try writing down the code myself.
function removeExtremes(arr) {
let shortestLen = 20;
let longestLen = 0;
let shortestIdx = 0;
let longestIdx = 0;
for (let i = 0; i < arr.length; i++) {
if (arr[i].length >= longestLen) {
longestLen = arr[i].length
longestIdx = i;
}
if (arr[i].length <= shortestLen) {
shortestLen = arr[i].length
shortestIdx = i;
}
}
let result = [];
for (let i = 0; i < arr.length; i++) {
if (i !== longestIdx && i !== shortestIdx) {
result.push(arr[i]);
}
}
return result;
}
In the first loop, the code iterates through the given array and if the length of the element is larger than the initial value 0, the longesLen becomes the length of the longer element we are currently at. The second for loop then is a loop that iterates through the array to find out the shortest element in the array. We use <= and >= to delete out the element that is located closest to the last when the longest and shortest element is more than one element. At the end of the first loop, the longest and the shortest index will be assgined to the variables: shortestLen & longestLen.
Now in the second loop, we assign a new array to the variable "result." The loop then iterates through the array again and only if the current 'i' or index the loop is checking on is not equal to the extreme elements which is the shortlesIdx & longestIdx, the element is pushed into the 'return' array. Lastly, we return the array: result.
output = removeExtremes(['where', 'is', 'the', 'longest', 'word']);
console.log(output); // --> ['where', 'the', 'word',]
Above is an example on how an array will turn into when it is given into the function we had made.