array cheatsheet

Array Cheatsheet

When attempting to secure your first job in programming, you’ll no doubt face a coding problem in the interview process, which will determine your performance. Whether the interview is in Java, C++ or Javascript, the basis remains the same. This is a test to see how strong we are in the foundations of programming logic. In this blog, we will use JavaScript.

In our interview questions, we commonly face 3 types of questions

  1. Arrays: An array is the most fundamental data structure, which stores elements at a contiguous memory location. This is one of the most common interview topics e.g., reversing an array, sorting the array, or searching for elements in an array.
  2. Strings: Another common interview question, however, is the skills learnt from working with arrays can be simply applied to strings.
  3. Data Structures: Strings and Arrays are linear data structures, other linear data structures include Linked Lists, Stacks and Queues. However, with all the data in the world structured and unstructured there are other data structures such as Binary Tree, Graphs, Sets and Table coding questions. The former is the most common.

JavaScript Methods:

In this blog we will be looking at the Array Methods and how to solve a question using these methods:

MethodDescriptionArgumentsReturnsmutates
.Slice( )Copies an array subsetIndices to copyA new arrayNo
.Concat ( )Creates an array with more valuesNew values/arrays to addA new arrayNo
.Splice ( )Inserts/deletes valueIndex to mutate/delete values to insertItems removedYes
. Join ( )Stringifies array contentStrings used to separate itemsA new stringNo
.Push( )Inserts new items at the end of the arrayItems to insertArray size afterYes
.Pop ( )Removes the last element of an arrayNoneLast array itemyes
.Unshift ( )Inserts new items at the start of the arrayItems to insertArray size afterYes
.Shift ( )Removes first item from arrayNoneFirst array itemYes
.Sort ( )Sorts existing arrayCallback to compare two itemsExisting array referenceYes
.Reverse ( )Reverses the order of items in the arrayNoneExisting array referenceYes
.Map ( )New array by transforming values Callback to transform one itemNew array with callback return valuesNo
.Filter ( )New array with values matching comparisonCallback to compare one itemNew array with original items where callback returned trueNo
.forEach ( )executes a provided function once for each array element. Callback to run logic for one itemNothingNo
.Reduce ( )Calculates one results value based on all itemsCallback to accumulate running resultFinal callback result valueNo
.Includes ( )Checks if exact value is in arrayValue to search forBooleanNo

The 3 most common methods would be:

The Reduce, Map and Filter Method.

Notes:

  1. The fifth column in our table, shows whether the JavaScript Method mutates the original array. It is bad practice to mutate the original array in real world applications. Therefore when using methods that mutate an array, we should create a new array for them.
  2. The .sort( ) method may surprise you at first use. On first attempt we would assume that the method will sort numbers however by default this method sorts a string variables alphabetically. We need to slightly manipulate it to take numbers into account. 

For Example, if we want to sort an array of ascending orders:

function getSecondLargest(nums) {
  return nums.sort();
}

console.log(getSecondLargest([5, 2, 9, 8, 24]));
// output: [2, 24, 5, 8, 9] 

We wouldn’t expect 24 to be outputted before 5, this is because the output we’re getting is a lexicographical sort. In other words, each integer is coerced into a string type and then the strings are compared character-by-character. Although 5 is numerically smaller than 24, lexicographically, it is larger therefore 24 appears more to the left of the array.

To rectify this, we add a function inside of the Sort method:

function getSecondLargest(nums) {
  return nums.sort((a, b) => a - b);
}

console.log(getSecondLargest([5, 2, 9, 8]));
// output: [2, 5, 8, 9, 24]

The array elements are sorted based on the relationship between each pair of elements “a” and “b” and the function’s return value. The three possible return numbers are: 

  1. < 0 (less than 0) – Sort “a” to be a lower index than “b”.  (Ascending order)
  2. Or 0 – “a” and “b” should be considered equal, and no sorting performed.
  3. Or > 0 (greater than 0) – Sort “b” to be a lower index than “a”.  (Descending order)

This works the way it does because whenever “a” is less than “b”, a negative value is returned, which results in the smaller elements always appearing to the left of the larger ones, in other words, ascending.

Where to practice interview questions?

  1. Codewars
  2. Hackerrank
  3. LeetCode (intermediate – advanced)

There are many other sites where you can practise these questions. The take-home message is being consistent, whether once a day, or whatever suits you will improve your programming logic. Good luck and all the best!

‘Kash works as a full-stack software developer at WayMaker Digital, helping clients to solve business and technology challenges.

WayMaker Digital provides technology consulting, product design and information products, that enable our clients to consistently thrive and innovate to meet user needs. The quality of our experiences and ideas set us apart when it comes to service delivery, customer experience design and product development. 

Our team of consultants have built digital experiences for leading brands with complex business scenarios ranging from startup companies to public services and from telecoms to e-commerce; no project deliverable is too complex.

Our approach: we adopt human-centred & design thinking models to solve complex business challenges, which ensure our clients are on top of their business.

Do you have a question or an enquiry; you want to discuss a project or need a free consultation? Give us a shout here.

Share with Friends

Leave a Comment

Your email address will not be published.

Scroll to Top