Interview Questions on Javascript
Quick Questions to check basic conceptual knowledge.
Question 2
How would you remove duplicate members from an array? Input: [1, 1, 3, 5, 8, 7, 3, 8, 99] Output: [1,5,7,3,8,99] This can also be done in a similar way creating nested loop. Check each number’s existence and keep a counter, if the counter is equal to 0, then add that number into a new array. This solution can be implemented in any language and also using while, do while loops as well.
Javascript:
let arrayWithDuplicates = [1, 1, 3, 5, 8, 7, 3, 8, 99];
let arrayLengthWithDuplicates = arrayWithDuplicates.length;
let arrayWithUniqueValues = [];
let counter = 0;
for (i = 0; i < arrayLengthWithDuplicates; i++) {
counter = 0;
for (j = i + 1; j < arrayLengthWithDuplicates; j++) {
if (arrayWithDuplicates[i] === arrayWithDuplicates[j]) {
counter++;
}
}
if (counter === 0) {
arrayWithUniqueValues.push(arrayWithDuplicates[i]);
}
}
console.log('With duplicate values : ' + arrayWithDuplicates);
console.log('With unique values : ' + arrayWithUniqueValues);
One of my favorite npm module is lodash. This whole loop written above can be done in one line using uniq function of lodash.
NodeJS using lodash:
const _ = require(‘lodash’);
let arrayWithDuplicates = [1, 1, 3, 5, 8, 7, 3, 8, 99];
let arrayWithUniqueValues = _.uniq(arrayWithDuplicates);
console.log('With duplicate values : ' + arrayWithDuplicates);
console.log('With unique values using lodash : ' + arrayWithUniqueValues);