tricky javascript interview questions and excerise

How to get an array of unique values from an array containing duplicates

Here is the solution for the same.

//find unique element in an array

Array.prototype.unique = function() {
    var unique = [];
    for (var i = 0; i < this.length; i++) {
        if (unique.indexOf(this[i]) == -1) {
    return unique;

var a=['1','2','3','2','5','2'];

How to compare 2 arrays are equal

Lets assume we have 2 arrays a & b. Many would start comparing a.length() with b.length. Upon equal then put a loop and start checking for each item.
better solution would be is to use join () :)

The join() method joins the elements of an array into a string, and returns the string.
String comparisons are always easy.

var a = ['1','2','3','2','5','2'];
var b = ['3','2','3','2','5','2'];
console.log('both arrays are same');
console.log('they are not')

Other solution being

function equal(arr1, arr2) {
    var i = arr1.length;
    if (i === 0 || i !== arr2.length) {
        return false;
    while (i--) {
        if (arr1[i] instanceof Array && arr2[i] instanceof Array) {
          if (!equal(arr1[i], arr2[i])) {
            return false;
        } else if (arr1[i] !== arr2[i]) {
          return false;

    return true;
if (!equal([1, [2]], [1, [3]])) {
  console.log("arrays aren't equal");
} else {
  console.log("arrays are equal");


I Am suresh(suresh kumar )a Web developer,Freelancer,webdesigner,UI developer from bangalore. Got 6+ yrs of IT experience . I specialize in standards-based XHTML, CSS and JavaScript web development. Each site I develop is built to be search engine friendly (SEO), using the latest development principles and techniques.

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *