Reputation: 655
i have a sample json array that contains a list of employeeId's
[{"employeeId": "20180000002"},{"employeeId": "20180000001"},{"employeeId":"20180000003"},{"employeeId": "20180000000"}]
wanted to get the last id which is employeeId":"20180000003
$.ajax({
url:'api/applicants/getwatchers',
type:'GET',
success: function(data){
watcherId = (data[data.length-1].employeeId || watcherId);
newWatcherId = parseInt(watcherId) + 1;
console.log(watcherId);
}
});
but the console.log was employeeId": "20180000000
Upvotes: 0
Views: 1357
Reputation: 36703
Use Math.max()
on the array of employeeId
using the spread operator.
var maxId = Math.max(...data.map(el=>el. employeeId)); // Will give you the max ID
watcherId = (maxId || watcherId);
newWatcherId = parseInt(watcherId) + 1;
console.log(watcherId);
Upvotes: 0
Reputation: 68393
wanted to get the last id which is employeeId":"20180000003
By last id, if you meant largest id (generated last by the system), then use Math.max.apply
and map
var arr = [{"employeeId": "20180000002"},{"employeeId": "20180000001"},{"employeeId":"20180000003"},{"employeeId": "20180000000"}];
watcherId = Math.max.apply( null, arr.map( s => +s.employeeId ) );
watcherId
is already a Number
, no need to do parseInt
, so the newWatcherId becomes
newWatcherId = watcherId + 1;
Upvotes: 3
Reputation: 429
You can sort the array in descending order and then get the first one as shown below:
list = [{"employeeId": "20180000002"},{"employeeId": "20180000001"},{"employeeId":"20180000003"},{"employeeId": "20180000000"}];
sortedIds = list.map(emp => emp.employeeId) // map the array to empIds.
.sort((a, b) => b - a)[0]; // sort desc.
lastId = sortedIds[0];
Upvotes: 0
Reputation: 953
You need to sort the array before you grab the last element if you want to get the largest number.
$.ajax({
url:'api/applicants/getwatchers',
type:'GET',
success: function(data){
data.sort((a,b) => b.employeeId - a.employeeId)
watcherId = (data[data.length-1].employeeId || watcherId);
newWatcherId = parseInt(watcherId) + 1;
console.log(watcherId);
}
});
It's possible I got the sort backwards - I always do that haha. In which case try:
data.sort((a,b) => a.employeeId - b.employeeId)
Upvotes: 0