var array1 = [4,2];
var array2 = [1,3];
var concatArray = array1.concat(array2);
// iteration 1
concatArray_min = Math.min.apply(Math,concatArray);
var result = [concatArray_min];
var index = concatArray.indexOf(concatArray_min);
delete concatArray[index];
console.log(concatArray); // returns [4,2,3]
console.log(result); // returns [1]
// iteration 2
concatArray_min = Math.min.apply(Math,concatArray);
console.log(concatArray_min); // returns NaN
result.push(concatArray_min);
index = concatArray.indexOf(concatArray_min);
delete concatArray[index];
console.log(concatArray); // returns [4,2,3]
console.log(result); // returns [1,NaN]
I am trying to merge two arrays and then sort them. I first concatenate the arrays and then delete the minimum from the unsorted concatenated array and push the minimum into the resulting array. This works at first, but fails for the second iteration as concatArray_min
shows to be NaN
. Perhaps the problem is in using Math.min.apply.(Math,concatArray)
to get the minimum value and using delete
to delete the element? Is there an alternative to this approach without using .sort()?