JSON array is var ParamArr = [1,2,3,4]
In the above array I want to check particular number contains in that array
I tried this but not working
if (!ParamArr.includes(4)) {
ParamArr.pop(4);
}
JSON array is var ParamArr = [1,2,3,4]
In the above array I want to check particular number contains in that array
I tried this but not working
if (!ParamArr.includes(4)) {
ParamArr.pop(4);
}
you have it almost correct, but you have a logical issue with your solution. you need to check if array contains the element. so you need to use condition ParamArr.includes(4)
and not !ParamArr.includes(4)
var ParamArr = [1,2,3,4];
if (ParamArr.includes(4)) {
ParamArr.pop(4);
}
console.log(ParamArr);
Add a simple function like this:
function isInArray(value, array) {
return array.indexOf(value) > -1;
}
And check with:
isInArray(4, ParamArr);
jQuery has a utility function for this:
$.inArray(value, array)
Returns index of value
in array
. Returns -1
if array
does not contain value
.
Also check How do I check if an array includes an object in JavaScript?
div {
color: blue;
}
span {
color: red;
}
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery.inArray demo</title>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
<div>"John" found at <span></span></div>
<div>4 found at <span></span></div>
<div>"Karl" not found, so <span></span></div>
<div>"Pete" is in the array, but not at or after index 2, so <span></span></div>
<script>
var arr = [4, "Pete", 8, "John"];
var $spans = $("span");
$spans.eq(0).text(jQuery.inArray("John", arr));
$spans.eq(1).text(jQuery.inArray(4, arr));
$spans.eq(2).text(jQuery.inArray("Karl", arr));
$spans.eq(3).text(jQuery.inArray("Pete", arr, 2));
</script>
</body>
</html>
Here you go with a solution
var ParamArr = [1,2,3,4];
if (ParamArr.indexOf(4) >= 0) {
ParamArr.pop(4);
}
console.log(ParamArr);
Hope this will help you.
plain old javascript
var tempArray = [1,12,13,14,4];
var elemToBeFound=tempArray[4]; //get the last elem in this ex
if(tempArray.indexOf(elemToBeFound) > -1){ //means it is present in the array
var indexOfElem=tempArray.indexOf(elemToBeFound);
// do what you want to do . you have the index in that array
}