Created
October 4, 2016 21:35
-
-
Save ValentynaGorbachenko/54e64e264ce29bb1e72453a400956bcb to your computer and use it in GitHub Desktop.
array_dups_sort created by ValentynaGorbachenko - https://repl.it/DoVE/1
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Implement function with 1 argument typeof <Array> | |
* 1. function should delete all duplicating elements | |
* 2. function should remove all not Number values | |
* 3. function should sort array from the largest to the smallest number. | |
* For example: given array [1, 1, 3, 2, 'qwe', 6, true, 4, 2], result function should return [6, 4, 3, 2, 1] | |
*/ | |
var arrayNotSorted = ['ggg', 'rtty', 1, 1, 1, 3, 2, 6, true, 4, 2];//I added few elements | |
var arraySorted; // If we like to save the incoming data | |
function myFuncSort(myArray) { | |
if (myArray instanceof Array){ // (Array.isArray(myArray)) another condition | |
var myArrayTemp = myArray.slice(); // coping the incoming array | |
// #2 version uses undefined | |
// Number check #2 | |
for(let i=0; i<myArrayTemp.length; i++){ | |
if (typeof myArrayTemp[i] !== 'number') { // checking if array element is not a number | |
myArrayTemp[i] = undefined; // if(typeof myArrayTemp[i] !=== 'number' || isNaN(myArrayTemp[i])) | |
} | |
} | |
// Duplicates check #2 | |
for(let i=0; i<myArrayTemp.length; i++){ | |
if (myArrayTemp[i] != undefined){ | |
for(let j=i+1; j<myArrayTemp.length; j++){ | |
if (myArrayTemp[i] == myArrayTemp[j] && myArrayTemp[j] != undefined){ // deleting all duplicated elements | |
myArrayTemp[j] = undefined; | |
} | |
} | |
} | |
} | |
// Deleting undefined #2 | |
myArrayTemp = myArrayTemp.filter(function(elem){ | |
if (elem != undefined){ | |
return elem; | |
} | |
}); | |
// #1 version uses method splice, which might be a bit heavy if array has a big number of elements | |
/* | |
// Number check #1 | |
for(var i=0; i<myArrayTemp.length; i++){ | |
if (typeof myArrayTemp[i] !== 'number') { // checking if array element is not a number | |
myArrayTemp.splice(i--,1); | |
} | |
} | |
// Duplicates check #1 | |
for(var i=0; i<myArrayTemp.length; i++){ | |
for(var j=i+1; j<myArrayTemp.length; j++){ | |
if (myArrayTemp[i] == myArrayTemp[j]){ // deleting all duplicated elements | |
myArrayTemp.splice(j--,1); | |
} | |
} | |
} | |
*/ | |
// Sort in the reverse order #1 and #2 | |
myArrayTemp.sort(function(a, b){return b-a}); // reversing the array elements | |
return myArrayTemp; | |
} else { | |
// Error message | |
console.log("Error - incoming data is not an array!"); | |
} | |
} | |
console.log(arrayNotSorted); | |
arraySorted = myFuncSort(arrayNotSorted); | |
console.log(arrayNotSorted); | |
console.log(arraySorted); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment