I’m trying to write a script that chooses three items at random from a list of objects, alphabetizes them by one field, and then displays the alphabetized values of another field. So far I can get it to choose the items randomly and show them, but it’s still not sorting. Here’s my code:
function random_text() {};
var random_text = new random_text();
var number = 0;
random_text[number++] = {
show: "Bob",
sort: "A"
}
random_text[number++] = {
show: "Casey",
sort: "B"
}
random_text[number++] = {
show: "Dan",
sort: "C"
}
random_text[number++] = {
show: "Alfred",
sort: "D"
}
var random_number = Math.floor(Math.random() * number);
var random_number1 = Math.floor(Math.random() * number);
var random_number2 = Math.floor(Math.random() * number);
if (random_number !== random_number1) {
var name1 = random_text[random_number1].show;
} else {
var name1 = "";
}
if (random_number !== random_number2 && random_number1 !== random_number2) {
var name2 = random_text[random_number2].show;
} else {
var name2 = "";
}
var name3 = random_text[random_number].show;
var objs = [name1 + " " + name2 + " " + name3];
objs.sort(function (a, b) {
var nameA = a.sort.toLowerCase(),
nameB = b.sort.toLowerCase()
if (nameA < nameB) //sort string ascending
return -1
if (nameA > nameB) return 1
return 0 //default return value (no sorting)
})
document.write(objs.sort());
Thanks in advance for the help. If there’s any way I can clean up the code, I appreciate tips on that, too.
See http://jsfiddle.net/Nc2Je/
Edit:
You do some weird things:
1- Why do you create an empty function and then you overwrite it with an instance of itself?
2- If you want an object which works like an array, why don’t you use arrays instead of setting array-like properties to
random_text?3- You should use the array
random_numbersinstead of those variables:4- Instead of those weird checks, you should ensure that your random number is different than the previous random numbers. With your checks, maybe the three random numbers are the same, so you will have only one name.
5- Why do you create an array which has only one element (a string)?
6- I didn’t use your following code because I have never used that, so I wrote my own sorting function.
7- Once you have sorted your objects, if you want to write them you should use
document.write(objs)withoutsort().Edit 2:
alphabetized.getNamesreturns an array.This way you can do
And if you want an string, you can do
alphabetized.getNames().join(" ");