Reputation: 390
Hello guys i cant find actually info about convert string to array and after check them.Im trying check have this post in usermeta or not. Before converting to array this string. But it doesnt work why?
$scope.like = function(id) {
PostService.GetUserMeta(user).then(function(data) {
var likes = '290 270'
var check_likes = likes.split(" ");
if (check_likes != id) {
$http.jsonp('http://somesite.com/api/userplus/update_user_meta_vars/', {
params: {
like_post: id + ',' + likes,
callback: "JSON_CALLBACK"
}
}).success(function(data) {
console.log('Id added to array');
});
} else {
console.log('ID already in array');
}
})
}
Upvotes: 0
Views: 67
Reputation: 14159
You can't compare an object of type Array
to a primitive data type like your id
parameter.
Try wrapping your code inside a loop like so:
for(i = 0; i < check_likes.length; i++){
if (check_likes[i] != id) {
$http.jsonp('http://somesite.com/api/userplus/update_user_meta_vars/', {
params: {
like_post: id + ',' + likes,
callback: "JSON_CALLBACK"
}
}).success(function(data) {
console.log('Id added to array');
});
} else {
console.log('ID already in array');
}
}
Upvotes: 0
Reputation: 133403
The problem lies in statement
if(check_likes != id)
Here check_likes
is an array thus it will never be equal to id
I think you need to create a number array.
var check_likes = likes.split(" ").map(Number);
Then you can use .indexOf() to check whether id
exists in an array, it returns the first index at which a given element can be found in the array, or -1
if it is not present.
if (check_likes.indexOf(id) == -1){
$http.jsonp(.....)
}else{
console.log('ID already in array');
}
Upvotes: 3
Reputation: 690
Try this code:
$scope.like = function(id) {
PostService.GetUserMeta(user).then(function(data) {
var likes = '290 270'
var check_likes = likes.split(" ");
if (check_likes.indexOf(id) == -1) {
$http.jsonp('http://somesite.com/api/userplus/update_user_meta_vars/', {
params: {
like_post: id + ',' + likes,
callback: "JSON_CALLBACK"
}
}).success(function(data) {
console.log('Id added to array');
});
} else {
console.log('ID already in array');
}
})
}
After splitting likes
string you have an array of 2 strings, and you should check that your id param is not in that array to execute your request. The !=
would not work
Upvotes: 0