简体   繁体   中英

Find biggest and smallest array Javascript

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?

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)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM