jswoody
jswoody

Reputation: 27

How to find the order changed contents in arrays using javascript?

    For Ex : original array : a =[1,2,3,4,g,5] 
    if the user wrongly entered the above array like this :   a = [2,1,3,4,g,5] 

How to find the position changed element from the original array list using javascript ?(i.e. [1,2] have been changed).

Upvotes: 2

Views: 57

Answers (4)

Suchit kumar
Suchit kumar

Reputation: 11859

var a1 = [1, 2, 3, 4, 5];
var a2 = [2, 1, 3, 4, 5];
var c=[];
a1.map(function(num,i){

          if(num !==a2[i]){
              c.push(num);
          } 
})
console.log(c);

Upvotes: 1

Jackson Ray Hamilton
Jackson Ray Hamilton

Reputation: 9466

// Try entering this at the prompt: [2, 1, 3, 4, 'g', 5]

var original = [1, 2, 3, 4, 'g', 5],
    input = eval(prompt('Enter an array please.'));

input.forEach(function (element, index) {
    var expected = original[index];
    if (element !== expected) {
        // They are different.
        // Logic to handle the difference goes here. Example:
        console.log('Elements were different; ' +
                    'expected `' + expected + '\', ' +
                    'got `' + element + '\'.');
    }
});

Upvotes: 2

Binary Brain
Binary Brain

Reputation: 1211

If you have two arrays with the same size:

var a1 = [1, 2, 3, 4, 5];
var a2 = [2, 1, 3, 4, 5];
var diff = [];

for(var i = 0, l = a1.length; i < l; i++) {
    if (a1[i] !== a2[i]) {
        diff.push(a1[i]);
    }
}

And the diff array contains the result you want.

Upvotes: 2

Girish
Girish

Reputation: 12127

try this

var a = [1, 2, 3, 4, "g", 5];
var b = [2, 1, 3, 4, "g", 5];
var c = [];
a.forEach(function(v, i){
  if(v !== b[i])
    c.push(v);
});
console.log(c);

Upvotes: 2

Related Questions