Reputation: 3
I have my array like callsData[] which contains objects like following:
{
"caller_id": "110",
"Channel": "SIP/Kam-SBC-0000001c",
"AccountCode": "1004",
"Server": "192.168.1.36",
"Callee": "109",
"connected_line": "109",
"Uniqueid": "145712272845",
"DestChannel": "SIP/Kam-SBC-0000001d",
"DestUniqueid": ["3432423423423","123123123","312321312"]
}
I want to find index of object where my value 3432423423423 is present in the DestUniqueid array.
Upvotes: 0
Views: 84
Reputation: 65873
Loop over the main array and upon each iteration, check the DestUniqueid property to see if it contains the value you seek:
function findIndex(valToFind){
for(var i = 0; i < callsData.length; ++i){
if(callsData[i].DestUniqueid.indexOf(valToFind) >= 0) {
return i;
}
}
}
Upvotes: 0
Reputation: 8926
Using Array#find
function:
var index;
callsData.find(function(el, i) {
if (el.DestUniqueid.indexOf('3432423423423') != -1) {
index = i;
return true;
}
})
console.log(index); // index that you need
Also you can use Array#filter
function to get all elements with DestUniqueid
that you need:
var arr = callsData.filter(function(el){
return el.DestUniqueid.indexOf('3432423423423') != -1;
});
console.log(arr); // array of callsData with your DestUniqueid
Upvotes: 0
Reputation: 3751
var x = {
"caller_id": "110",
"Channel": "SIP/Kam-SBC-0000001c",
"AccountCode": "1004",
"Server": "192.168.1.36",
"Callee": "109",
"connected_line": "109",
"Uniqueid": "145712272845",
"DestChannel": "SIP/Kam-SBC-0000001d",
"DestUniqueid": ["3432423423423","123123123","312321312"]
}
x.DestUniqueid.indexOf("3432423423423")
> 0
x.DestUniqueid.indexOf("312321312")
> 2
So you could just call index of in a function
var findIndex = function(obj, myVar){
return obj.DestUniqueid.indexOf(myVar)
}
and call it like:
findIndex(x, "312321312")
>2
Upvotes: 0
Reputation: 4660
Here is a simple function to accomplish that in linear time.
How large is the array? Is it sorted in any way?
function findIndex (array, target) {
for (var i = 0; i < array.length; i++){
if (array[i].DestUniqueid) === target){
return i;
}
return null;
}
}
Upvotes: 0
Reputation: 67217
Try to write a simple for loop
,
for(var i=0;i<callsData.length;i++){
if(callsData[i].DestUniqueid.indexOf("3432423423423") > -1)
break;
}
console.log(i + " is the index of element with value 3432423423423");
If you want it as a function then just write like,
function getIndex(val){
for(var i=0;i<callsData.length;i++){
if(callsData[i].DestUniqueid.indexOf(val) > -1)
break;
}
return i;
}
console.log(getIndex("3432423423423") + " is the index of element with value 3432423423423");
Upvotes: 1