Interview Questions on Javascript

Quick Questions to check basic conceptual knowledge.

Question 3

To sort the items of an array.
Input: [1, 4, 2, 5, 6, 7, 3, 8, 99]
Output: [1,2,3,4,5,6,7,8,99]

This is one question asked as part of data structure as well. People might ask to write algorithm to understand candidate’s approach towards the solution. As of my other solutions, this can also be done through nested loops and similar approach can be used in other language’s as well.

Javascript:


	let sampleArray  = [1, 4, 2, 5, 6, 7, 3, 8, 99];
	let arrayLength = sampleArray.length;
	let tmpValue;
			
	console.log('Unsorted Array: ' + sampleArray);
	for (i = 0; i <= arrayLength - 1; i++) {
		for (j = i + 1; j <= arrayLength - 1; j++) {
			if (sampleArray[i] > sampleArray[j]) {
				tmpValue = sampleArray[i];
				sampleArray[i] = sampleArray[j];
				sampleArray[j] = tmpValue;         
			}
		}
	}
			
	console.log('Sorted Array: ' + sampleArray);
									

One of my favorite npm module is lodash. This whole loop written above can be done in one line using sort function of lodash.

NodeJS using lodash:

const _ = require('lodash');
let sampleArrayWithLodash  = [1, 4, 2, 5, 6, 7, 3, 8, 99];

console.log('Unsorted Array: ' + sampleArrayWithLodash);
console.log('Sorted Array using lodash: ' + _.sortBy(sampleArrayWithLodash));