Am comparing javascript array of elements with other elements within the same array. If elements are same means, i have to give same number for all the common elements. If the elements are different i have to give some different number for all the non identical elements in another element.
for example :
Array structure = [{Location, Date, Number}]
array = [{ 'LA','2017-12-01',1},
{ 'LA','2017-12-01',1},
{ 'NY','2017-12-01',2},
{ 'NY','2016-10-01',3},
{ 'LA','2017-12-01',1},
{ 'LA','2017-12-01',1},
{ 'LA','2017-12-01',1}]
In this array 'Number' is dynamic element, It should be populate on the following rules.
key1 = location + '-' +date;
Consider Key1 is the first element ( combination of location + date ). If the same key1 is present in the array, then 'Number' is common for all the same Key1.
In the above example {'LA','2017-12-01',1 } having the same number 1.
{ 'NY','2017-12-01',2} having the number 2. and
{ 'NY','2016-10-01',3}, having the number 3 because eventhough location is common but date is different.
Please find my code below.
var item = this.state.item;
var lines = item.order_items;
var count=1;
var key1;
var key2;
for(var i=0;i<lines.length;i++)
{
key1 = lines[i].location + '-' + lines[i].date;
for(var j=0;j<lines.length;j++)
{
key2 = lines[j].location + '-' + lines[j].date;
if( key1 === key2 )
{
lines[i].number=count;
this.setState({item:item});
}
else
{
count++;
lines[j].number=count;
this.setState({item:item});
}
}
}
Problem is, for loop is iterating multiple times - its keep on comparing the same element multiple times. how do i can solve this issue.
j<lines.lengthtoj<i