Toufic Batache Toufic Batache - 1 month ago 6
Javascript Question

Duplicate values in array cause a undefined to appear

I was making a js code that gets items from an array. One problem: items with same value return undefined or disappear. I tried many different things but nothing is working. Here is a jsfiddle : https://jsfiddle.net/76e40vqg/5/

var data =
[{"image":"link1","name":"Name1","address":"Address1","rate":"4.4"},
{"image":"link2","name":"Name2","address":"Address2","rate":"3.3"},
{"image":"link3","name":"Name3","address":"Address3","rate":"3.3"}
];

var restoName = [];
for(i = 0; i < data.length; i++){
if(restoName.indexOf(data[i].name) === -1){
restoName.push(data[i].name);
}
}

var restoAddress = [];
for(i = 0; i < data.length; i++){
if(restoAddress.indexOf(data[i].address) === -1){
restoAddress.push(data[i].address);
}
}

var restoRate = [];
for(i = 0; i < data.length; i++){
if(restoRate.indexOf(data[i].rate) === -1){
restoRate.push(data[i].rate);
}
}

var restoImage = [];
for(i = 0; i < data.length; i++){
if(restoImage.indexOf(data[i].image) === -1){
restoImage.push(data[i].image);
}
}

for(i = 0; i < restoName.length; i++){
document.getElementById('output').innerHTML += "Image : <a href='" + restoImage[i] + "'><div class='thumb' style='background-image:" + 'url("' + restoImage[i] + '");' + "'></div></a><br>" + "Name : " + restoName[i] + "<br>" + "Address : " + restoAddress[i] + "<br>" + "Rate : " + restoRate[i] + "<br>" + "Index" + "<br><hr>";
}

pid pid
Answer

This piece of code in the JS Fiddle:

if (restoRate.indexOf(data[i].rate) === -1)
{
    restoRate.push(data[i].rate);
}

Says literally, if there is not the value 3.3, push it into restoRate. Otherwise, don't push it.

In other words, the second 3.3 is not pushed because this is what you want (have implemented) and thus for index 3 there is no value and you get undefined.


EDIT: Proposed solution which probably is insufficient

To fix it, don't check for uniqueness, just like this (without the surrounding if()):

restoRate.push(data[i].rate);

It is not clear if this is what you need further down your code, so probably you need to rethink some parts of your code. In this we cannot help you, or better it calls for another, precise question with the other code.

Comments