Reputation: 7703
Please help to solve the undefined error coming in my console while running the below code
Please see this JSbin also http://jsbin.com/ONOwujA/1/edit
data = [
{key:"home",value:"hk1"},
{key:"home",value:"hk2"},
{key:"home",value:"hk3"},
{key:"home",value:"hk4"},
{key:"product",value:"pk1"},
{key:"product",value:"pk2"},
{key:"product",value:"pk3"},
{key:"product",value:"pk4"},
{key:"service",value:"sk1"},
{key:"service",value:"sk2"},
{key:"service",value:"sk3"},
{key:"service",value:"sk4"}
];
myFilteredKey=[];
for(i=0;i<=data.length;i++){
if(myFilteredKey.indexOf(data[i].key)!=-1){
myFilteredKey.push(data[i].key);
console.log(data[i].key);
}
}
Upvotes: 0
Views: 37
Reputation: 816414
Use i < data.length
. If the length is 3
, the maximum index is 2
.
Another problem with your code is that no element will be added to myFilteredKey
. Since the array is already empty, no element will satisfy the condition myFilteredKey.indexOf(data[i].key)!=-1
. Maybe you want to use === -1
instead, i.e. check whether the element is not in the array rather than whether it's in the array.
Upvotes: 1