Reputation: 102
I am working on Angular 2 with type script and came up with a very peculiar problem. I have a number array named empIds as
empIds = {1,5,6,9,2}
I have (a JSON Array) named empDetails (please note employeeId is string here)as
empDetails [{"employeeId":"1","employeeName":"Jhon"},
{"employeeId":"2","employeeName":"Ron"},
{"employeeId":"3","employeeName":"Van"}]
Now i have to find out the only JSON objects who's id match in number array. Here is what i wrote
for(let i=0;i<empDetails.length;i++){
if(empIds.indexOf(empDetails[i].employeeId)==0 ){
//Employee ID is present save that JSON object to some other JSON Array
i should get details for matched id (1 and 2)
}else{
//Did not match
do nothing
}
}
i did put console.log for both if and else. My loop never matches it always goes to else condition? Is there any possible solution?
Upvotes: 0
Views: 56
Reputation: 3166
var filtered = empDetails.filter( (e) => empIds.indexOf(parseInt(e.employeeId)) >= 0 );
If you don't care about support for Internet explorer, you can also use includes()
(See answer by Hopless)
Upvotes: 0
Reputation: 56
const newArray = empDetails.filter(item => empIds.includes(item.employeeId));
I think this is an ok way to get a new array with all the objects from empDetails that have the employeeId in empIds.
.includes() => returns true or false if the empIds contains the employeeId
.filter() => returns all the objects that were true on the include call
empIds = [2];
empDetails = [{"employeeId":1,"employeeName":"Jhon"},
{"employeeId":2,"employeeName":"Ron"},
{"employeeId":3,"employeeName":"Van"}]
with my code the new array would be this
[{"employeeId":2,"employeeName":"Ron"}]
because only employeeId = 2 is in empIds table
Upvotes: 0
Reputation: 834
The code logic is incorrect. Check index if its greater than -1 Should be as below
let empIds = [1, 5, 6, 9, 2];
let empDetails = [{ "employeeId": 1, "employeeName": "Jhon" },
{ "employeeId": 2, "employeeName": "Ron" },
{ "employeeId": 3, "employeeName": "Van" }]
for (let i = 0; i < empDetails.length; i++) {
if (empIds.indexOf(empDetails[i].employeeId) > -1) {
console.log("found");
console.log(empDetails[i])
}
}
Upvotes: 1