Proless
Proless

Reputation: 217

compare elements positions in first array with another array

i got stucked on a game when i need to compare two arrays. Both arrays contain numbers. First array got numbers sorted and second one has numbers in user order. What i try to achieve is : compare these arrays and find wrong position in user array(if exists) and return the number on wrong position.

What i have tryed:

var a = ["1","2","3","4","5"];
var d = ["1","2","3","5","4"];

function checkArrays( arrA, arrB ){

    if(arrA.length !== arrB.length) return false;

    var cA = arrA.slice().sort().join(","); 
    var cB = arrB.slice().sort().join(",");

    return cA===cB;

}

EDIT: randomArrayGenerated.push(generateRandoms(0,99)); - where generateRandoms is a function. While in for i push in randomArrayGenerated some numbers so the length of array varies.

correctOrderArray.push(randomArrayGenerated.sort(function(x, y){return x-y})); - adding in correctOrderArray , the elements from random array but sorted.

userArray.push(userOrder); - where userOrder is a variable which gets value from an input.

IF userArray.length == correctOrderArray.length - i'd like to compare these arrays using correctOrderArray.find(function(a, b){ return a !== userArray[b] })

Why doesnt work? (Uncaught TypeError: undefined is not a function)

Upvotes: 1

Views: 2307

Answers (2)

Sam Greenhalgh
Sam Greenhalgh

Reputation: 6136

Its just a loop.

function checkArrays( arrA, arrB ){
    for(var i = 0; i < arrA.length; i++) { if(arrA[i] !== arrB [i]) return arrB [i] };
}

http://jsfiddle.net/hL257bh6/

If you're allowed to use ECMAScript 6

a.find(function(v, i){ return v !== d[i] })

Upvotes: 0

Shiala
Shiala

Reputation: 486

var a = ["1","2","3","4","5"];
var d = ["1","2","3","5","4"];
var wrongPositioned = false;

function checkArrays( arrA, arrB ){

    if(arrA.length !== arrB.length) return false;

    for (var i = 0; i< arrA.length; i++) {
        if (arrA[i] !== arrB[i]) {
           wrongPositioned = {
               position: i, 
               value: arrA[i],
               userValue: arrB[i],
               valuePositionInUser: arrA.indexOf(arrB[i])
           };
           break;  
        }
    }

    return wrongPositioned;

}

Upvotes: 1

Related Questions