Algorithm 202: Where I Belong in 3 Ways
NJOKU SAMSON EBERE
Posted on March 19, 2020
If you are to queue according to your height, you will need to stand between someone that only you is taller than and someone that only you is shorter than - that is where you belong
.
This also applies when finding the position of an element in array where it is to be inserted.
whereIBelong([1, 2, 3, 4], 3.5); // 3
whereIBelong([13, 23, 33, 45], 55); // 4
In how many ways can you determine the position of a given element?
Let me dish out to you 3 ways and I will give you a hint to one more in the conclusion
Prerequisite
This article assumes that you have basic understanding of javascript's array methods.
Let's do this using:
- push(), sort(), indexOf()
function whereIBelong(array, value) {
let newArray = array.push(value);
let sortedArray = array.sort((a, b) => a - b);
return array.indexOf(value);
}
- for...in...loop, break
function whereIBelong(array, value) {
let newArray = array.sort((a, b) => a - b);
let position = "";
for (char in newArray) {
if (newArray[char] > value) {
position = char;
break;
} else {
position = newArray.length;
}
}
return position;
}
- filter(), for...of...loop, indexOf()
function whereIBelong(array, value) {
let newArray = array.sort((a, b) => a - b);
let maxValue = 0;
// collect all array values less than the given value
let smallerValues = newArray.filter(char => value > char);
if (smallerValues === []) {
return 0;
}
for (char of smallerValues) {
char > maxValue ? (maxValue = char) : maxValue;
}
return newArray.indexOf(maxValue) + 1;
}
Conclusion
There are many ways to solve problems programmatically. You can also achieve this using the while...loop
construct - increment it's counter
for every element of the array that the given value is greater than. I will love to know other ways you solved yours in the comment section.
If you have questions, comments or suggestions, please drop them in the comment section.
You can also follow and message me on social media platforms.
Thank You For Your Time.
Posted on March 19, 2020
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.