How could I check to see if the next element in an array is the same name as the current element
I have an array and I'm trying to check to see if the array in the next slow is the same as the current slow in the array.
Here is my logic so far:
$("#container").append("<table border='1' id='main-table'></table>");
var strNames = ["dennis", "dennis", "d0开发者_JAVA百科0d", "sweet"].sort();
var categories = [];
for (var i = 0; i < strNames.length; i++) {
if (strNames[i] == strNames[i+1])
categories[i] = strNames[i];
console.log(categories[i]);
if (categories.length > 1) {
$("#main-table").append("<tr class='main-table-row'><td><div class='expandTableCell' toggle='false'></div></td></tr>");
for (var x = 0; x < categories.length; x++)
if (x == 0)
$("#main-table tr.main-table-row td div.expandTableCell").append("<div class='expandTableCellHeader'>" + categories[x] + "</div>");
else
$("#main-table tr.main-table-row td div.expandTableCell").append("<div class='expandTableCellData'>" + categories[x] + "</div>");
} else
$("#main-table").append("<tr class='main-table-row'><td>" + strNames[i] + "</tr>");
}
I need it to check the next index of an array and if it has the same name, store it into categories which ends up building a tree. If you need more information I can try to provide more.
I had to change your logic a bit, but here you go:
Live Demo
$("#container").append("<table border='1' id='main-table'></table>");
var strNames = ["dennis", "dennis", "d00d", "sweet"].sort();
var categories = [];
for (var i = 0; i < strNames.length; i++) {
var name = strNames[i];
if (typeof(categories[name]) == 'undefined') categories[name] = 1;
else categories[name] += 1;
}
for (var name in categories) {
var val = categories[name];
if (val > 1) {
$("#main-table").append("<tr class='main-table-row'><td><div class='expandTableCell' toggle='false'></div></td></tr>");
for (var x = 0; x < val; x++)
if (x == 0) $("#main-table tr.main-table-row td div.expandTableCell").append("<div class='expandTableCellHeader'>" + name + "</div>");
else $("#main-table tr.main-table-row td div.expandTableCell").append("<div class='expandTableCellData'>" + name + "</div>");
} else $("#main-table").append("<tr class='main-table-row'><td>" + name + "</tr>");
}
I believe that
if (strNames[i] == strNames[i+1]) categories[i] = strNames[i];
will fail when i points to the last element of the 'strNames' array. An exception will be thrown, since i+1 will point out of the array.
Otherwise, I do not see any problem on this "if". To avoid this error you need to make your for loop to be something like
for (var i = 0; i < strNames.length-1; i++)
I also see another problem in the 'if' comparison if (categories.length > 1)
Doesn't it have to be if (categories.length >= 1)
? If you leave it as it is, then when categories length is 1, then block is not entered.
Other than doing this:
if (i + 1 < strNames.length
i + 1 < categories.length
&& categories[i] == strNames[i+1])
You should be on your way
精彩评论