Reputation: 196
I have to do a ForEach from a json file (actually 2 json files) for this reason Im doing 2 forEach, the code is
<head>
<style>
table {
font-family: arial, sans-serif;
border-collapse: collapse;
width: 100%;
}
td, th {
border: 1px solid #dddddd;
text-align: left;
padding: 8px;
}
tr:nth-child(even) {
background-color: #dddddd;
}
</style>
</head>
<body>
<h2>HTML Table</h2>
<table>
<tr>
<th>Company</th>
<th>Contact</th>
<th>Country</th>
</tr>
<% alist.forEach(function(alist_items){%>
<% alist_b.forEach(function(alist_items_b){%>
<%if(alist_items_b.AY==alist_items.CI){ %>
<tr>
<td bgcolor="#FF0000"><%= JSON.stringify(alist_items_b) %></td>
</tr>
<% }else{ %>
<tr>
<td><%= JSON.stringify(alist_items_b) %></td>
<% } %>
</tr>
<% }) %>
<% }) %>
</table>
The json files are:
[
{
"CI": "10"
},
{
"CI": "11"
},
{
"CI": "12"
},
{
"CI": "13"
},
{
"CI": "14"
},
{
"CI": "15"
},
{
"CI": "16"
},
{
"CI": "17"
},
{
"CI": "18"
},
{
"CI": "19"
},
{
"CI": "20"
}
]
and
[\[
{
"AY": "10"
},
{
"AY": "11"
},
{
"AY": "12"
},
{
"AY": "13"
},
{
"AY": "14"
}
I need show in red the repeat values, and normally the others, but how you can see in 1 picture, the anothers values are repeat how many times as repeat. I need to show just one time the others values
Thanks
Upvotes: 0
Views: 105
Reputation: 295
Alright! First, we are merging both the array of objects into one. Second, iterate over the merged array and check duplicate values (it works like hash map). Third, insert a new attribute in every object called colorRed
(it indicates whether to color duplicate rows as red or not).
JS changes:
var a = []; //first array of object
var b = []; //second array of object
Array.prototype.push.apply(a, b); //merging both the arrays
//finding the number of occurences of all the values
//variable would hold all the indexes of the array having same value
var c = new Object();
a.forEach(function (value, index) {
var vArr = Object.keys(value);
if (!c.hasOwnProperty(value[vArr[0]]))
c[value[vArr[0]]] = [];
c[value[vArr[0]]].push(index);
c[value[vArr[0]]].forEach(function (cValue, cIndex) {
if (c[value[vArr[0]]].length > 1)
a[cValue].colorRed = true;
else
a[cValue].colorRed = false;
});
});
Now, after making changes in JS. The array iterated in template is simply array of objects containing whether or not to paint the row red. For better understanding you can simply do console.log(a);
and check the final array structure.
HTML changes:
<% a.forEach(function(val, ind) { %>
<tr>
<%if (val.colorRed) { %>
<td bgcolor="#FF0000">
<% } else { %>
<td>
<% } %>
<%= JSON.stringify(val) %></td>
</tr>
<% }) %>
Upvotes: 1