Algorithms: Useful Native Methods
Often solving technical interview problems is simply a matter of knowing which native methods to use. This is especially true for problems that involve manipulating strings or arrays. Here are some useful native methods for arrays and strings in JavaScript that can help with common tasks like sorting, searching, and manipulating data.
String Methods
.replace() & .replaceAll()
- Useful for replacing a substring with another substring.
- Can be used to replace all occurrences of a substring.
- can be combined with regex to perform more complex replacements.
const str = 'The quick brown fox jumps over the lazy dog.';
const newStr = str.replace('fox', 'cat');
console.log(newStr);
// Expected output: "The quick brown cat jumps over the lazy dog."
.slice()
- Useful for extracting a section of a string.
- Can be used to extract a substring from a string.
const str = 'The quick brown fox';
const subStr = str.slice(4, 9);
console.log(subStr);
// Expected output: "quick"
.split()
- Useful for splitting a string into an array of substrings.
- Can be used to split a string by a certain character or substring.
const str = 'The quick brown fox';
const words = str.split(' ');
console.log(words);
// Expected output: Array ["The", "quick", "brown", "fox"]
.includes()
- Useful for checking if a string contains another string.
const sentence = 'The quick brown fox jumps over the lazy dog.';
const word = 'fox';
console.log(sentence.includes(word));
// Expected output: true
.indexOf()
Extremely useful for the classic needle-in-haystack problem.
Given two strings needle
and haystack
, return the index of the first occurrence of needle
in haystack
, or -1
if needle
is not part of haystack
.
This method returns the index of the first occurrence of a specified value in a string, or -1 if the value is not found.
Therefore this method can solve the problem just like so:
/**
* @param {string} haystack
* @param {string} needle
* @return {number}
*/
var strStr = function (haystack, needle) {
return haystack.indexOf(needle);
};
Which without the use of .indexOf()
would require a loop to iterate over the haystack
string and compare substrings of the same length as needle
to needle
itself.
/**
* @param {string} haystack
* @param {string} needle
* @return {number}
*/
var strStr = function (haystack, needle) {
if (haystack === needle) {
return 0;
}
for (i = 0; i < haystack.length - needle.length + 1; i++) {
const subString = haystack.substring(i, i + needle.length);
if (subString === needle) {
return i;
}
}
return -1;
};
.substring()
Note that substring
does not use camelCase as it is considered to be one word. This can trip you if you are in a situation where you must recall the method from memory without a linter.
.at() & .charAt()
Essentially the same method, but at()
is a newer method that is more versatile and can handle Unicode characters. Additionally at()
can be used to access characters from the end of the string by using negative indices, and returns undefined
if the index is out of range.
const str = 'abc';
console.log(str.at(0)); // Expected output: "a"
console.log(str.at(-1)); // Expected output: "c"
console.log(str.at(10)); // Expected output: undefined
console.log(str.charAt(0)); // Expected output: "a"
console.log(str.charAt(-1)); // Expected output: ""
console.log(str.charAt(10)); // Expected output: ""
Array Methods
.sort()
- Not useful for sorting numbers in ascending order, as it will sort them as strings.
- IS USEFUL for sorting arrays of strings which is useful for longest common prefix problems.
const months = ['March', 'Jan', 'Feb', 'Dec'];
months.sort();
console.log(months);
// Expected output: Array ["Dec", "Feb", "Jan", "March"]
Therefore given the problem:
Write a function to find the longest common prefix string amongst an array of strings.
If there is no common prefix, return an empty string "".
We can simplify that problem using the sort method:
/**
* @param {string[]} strs
* @return {string}
*/
var longestCommonPrefix = function (strs) {
strs.sort();
let firstString = strs[0];
let lastString = strs[strs.length - 1];
let index = 0;
for (index = 0; index < firstString.length; index++) {
if (firstString.charAt(index) !== lastString.charAt(index)) {
break;
}
}
return index == 0 ? '' : firstString.substring(0, index);
};
We only have to compare the first and last strings in the sorted array to find the longest common prefix, as we know that they are the most dissimilar strings in the array.
.every()
- Useful for checking if all elements in an array pass a certain test.
- Can be used to check if all elements in an array are the same.
const array1 = [1, 30, 39, 29, 10, 13];
console.log(array1.every((element) => element < 40));
// Expected output: true
.includes()
- Useful for checking if an array contains a certain element.
const array1 = [1, 2, 3];
console.log(array1.includes(2));
// Expected output: true
Comments
Recent Work
Basalt
basalt.softwareFree desktop AI Chat client, designed for developers and businesses. Unlocks advanced model settings only available in the API. Includes quality of life features like custom syntax highlighting.
BidBear
bidbear.ioBidbear is a report automation tool. It downloads Amazon Seller and Advertising reports, daily, to a private database. It then merges and formats the data into beautiful, on demand, exportable performance reports.