0

I am trying to figure out the best way to compare two arrays.

Essentially I want to know the biggest and smallest array for further processing. Here is my code for doing so thus far:

merge: function(arrOne, arrTwo) {

   if(arrOne == null || arrTwo == null) throw new Error();

    var bigArr = arrOne.length > arrTwo.length ? arrOne : arrTwo,
        smallArr = bigArr.length == arrOne.length ? arrTwo : arrOne;

    console.log(bigArr);
    console.log(smallArr);

}

While this works, I am guessing there has to be an easier and more efficient way of doing this. Any thoughts?

22
  • 1
    @techfoobar it will make it much more readable, OTOH Commented Mar 29, 2013 at 18:38
  • 1
    I would change your =='s to ==='s impressivewebs.com/why-use-triple-equals-javascipt Commented Mar 29, 2013 at 18:40
  • 1
    @JanDvorak Ahh. Very good. Didn't even think of that. Commented Mar 29, 2013 at 18:42
  • 1
    @SethenMaleno as I said, it's a mess. If someoneone used it in our codebase where if could have been used, I would get a huge ? and bludgeon that guy. Commented Mar 29, 2013 at 18:44
  • 1
    @Jazzepi note that referencing a non-existent property is not an error. console.log(window.foo) Commented Mar 29, 2013 at 18:50

2 Answers 2

1

The best way would be to not use a ternary, and write a normal condition.

var bigArr, smallArr;
if(arrOne.length > arrTwo.length){
    bigArr = arrOne;
    smallArr = arrTwo;
}else{
    smallArr = arrOne;
    bigArr = arrTwo;
}

Readable, fast, it's obviously bug-free.

If you really want to use a ternary operator (for example to avoid duplicate declaration and assignment after declaration), perhaps the correct solution would be to repeat (or cache) the condition:

var   bigArr = arrOne.length > arrTwo.length ? arrOne.length : arrTwo.length,
    smallArr = arrOne.length > arrTwo.length ? arrTwo.length : arrOne.length;

Somewhat readable, obviously bug free, assigns at declaration.

If you want to avoid if and condition duplication, it's still possible. However, the code is unreadable (mainly because the comma operator is used) and shouldn't be used in production code. It might still be useful for code golf, though, and I'll name the variables appropriately. Handle with care:

l=(a.length>b.length)?(s=b,a):(s=a,b)
Sign up to request clarification or add additional context in comments.

Comments

0

Your code will fail in cases where are there undefined values inbetween the array. If you need to handle such a condition, you might want to try a totally different approach.

var myArray = new Array();
myArray[100] = true;
console.log(myArray.length); // returns 101

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.