d2jsp
Log InRegister
d2jsp Forums > Off-Topic > Computers & IT > Programming & Development > Javascript Sorting Arrays
Add Reply New Topic New Poll
Member
Posts: 11,254
Joined: Nov 6 2004
Gold: 0.00
Mar 13 2017 09:16pm
i need help

I need to write a script that will take the following array ['scott',1,'sam','george',156,74,'Jazzy',197] and put all the numbers into a numbers array and all the names into a names array.
Each array will be in order. You must use the array as it is exactly written.

I have no idea how to do this
i hate this stupid class im taking..programming isnt my thing
can someone help me please

Member
Posts: 36,123
Joined: Jul 18 2008
Gold: 2,407.00
Mar 14 2017 04:13pm
Which part do you need help with? The sorting algorithm or breaking the arrays by names/numbers?
Member
Posts: 1,039
Joined: Jul 8 2008
Gold: 1,939.50
Mar 14 2017 04:28pm
Make three arrays and iterate through the initial array pulling out numbers into the number array and names into the name array. There other ways to do this, but this approach is straight forward.

var array = ['scott',1,'sam','george',156,74,'Jazzy',197];
var numbers = new Array();
var names = new Array();
array.forEach(function(item) {
if(typeof(item) == "number") {
numbers.push(item);
} else {
names.push(item);
}
});
numbers.sort();
names.sort();
Member
Posts: 918
Joined: Apr 23 2008
Gold: 18,517.00
Mar 15 2017 05:50pm
ditto as above, another version

Code

var arr = ['scott',1,'sam','george',156,74,'Jazzy',197]

var names = []
var nums = []

for(var x=0;x<arr.length;++x){
if(isNaN(arr[x])){
names.push(arr[x])
}else{
nums.push(arr[x])
}
}

names.sort()
numbers.sort()

console.log(names)
console.log(nums)
Go Back To Programming & Development Topic List
Add Reply New Topic New Poll