I hope I am not repeating an existing question, I have tried really hard to find what I need on the site, but now feel I need to ask the question, so here goes, I hope you guys can help me out :s
I have an array;
var 1Results = somecontent;
var 2Results = somecontent;
var 3Results = somecontent;
var 4Results = somecontent;
var nomResults = 1Results + 2Results + 3Results + 4Results;
I have a script that is supposed to weed out the duplicate numbers and display them (in sorted_arr);
var arr = nomResults;
var sorted_arr = arr.sort(); // You can define the comparing function here.
// JS by default uses a crappy string compare.
var results = [];
for (var i = 0; i < arr.length - 1; i++) {
if (sorted_arr[i + 1] == sorted_arr[i]) {
results.push(sorted_arr[i]);
}
}
This script doesn't work, however is I change the script to this;
var arr = [9, 9, 111, 2, 3, 4, 4, 5, 7];
var sorted_arr = arr.sort(); // You can define the comparing function here.
// JS by default uses a crappy string compare.
var results = [];
for (var i = 0; i < arr.length - 1; i++) {
if (sorted_arr[i + 1] == sorted_arr[i]) {
results.push(sorted_arr[i]);
}
}
It works fine, any ideas why .sort() won't work with my pre popluated array?
Any help would be greatly appreciated.
var nomResults = 1Results + 2Results + 3Results + 4Results;is not an array and 1Results is not a valid JavaScript identifier. It should not even parse. Did you mean to usevar nomResults = [Results1,Results2,...]?nomResultsis just a concatenation of the other variables. It's still not an array. It is just a single value, so there is nothing to "sort." Yourvar arrIS an array (multiple comma-separated values inside square brackets), so it can sort.[1,2,3]; this is not an array, it's a 6:1+2+3