JavaScript: How to compare elements in an array?

I. Palindrome

A common entry level interview question is to compare the elements within an array to meet a certain expectation. Typically this question is phrased as “Finding the palindromes” or reversing strings but the general idea involves manipulating data types within the array. An array is just list of strings, numbers or any other data types. We can iterate through every element in an array and compare it to meet an expectation, then return an output were the results are true. If you stumbled here looking for a StackOverflow post on how to find a palindrome here is the basis of that code.

function palindrome(string) {
return string == string.split("").reverse().join("")
// outputs a boolean due to the "==" operator
let i = 0while ( i < array.length ) {
// code logic

II. Sort

Another often asked question is how to sort elements in an array. The way to achieve this is through the sort() method for arrays. This works fine for strings but with numbers the first digit’s place from 1–10 is used to sort numbers.


There are many ways to manipulate the data in the array it all depends on the data type. The main take-away is to pay attention to your data through all stages of the function scope. What is my elements data type? What logic/comparison is being performed? What is my desired output? All are valid questions that should steer the construction of your code. Walk through it step by step, visualize the data, predict the output and consistently ask these questions while programming.

Related Links



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store