I have a JavaScript array:
var j_array = new Array();
j_arry=["class:1","division:a","class:5","class:3","division:b","division:c","division:d","class:10"];
I need to find how many times the class is coming and its array key, so I use:
found = $.inArray('class', j_array); ` But it returns `-1`;
Then I use:
var search = 'class';
$.each([j_array], function(index, value){
$.each(value, function(key, cell){
if (search.indexOf(cell) !== -1)
console.log('found in array '+index, cell);
});
});
But that is also wrong. How do I solve this?
From this array I want to get the following:
Class coming 4 times, at key 0, 2, 3, and 7
I want to make a separate array of class only, that is,
new_array = ["class:1", "class:2", "class:3", "class:10"];
Currently there are four classes in j_array
. How can I get the Nth class value
That is, 1st class value ="class:1"
, 2nd class value="class:5"
, etc.
count("$. value == '" + $(this). val() + "'") > 1) { // If more than 1 have the same value than highlight this textbox and display an error message $(this). addClass('duplicate'); $('#custom-field-validator').
pop() function: This method is use to remove elements from the end of an array. shift() function: This method is use to remove elements from the start of an array. splice() function: This method is use to remove elements from the specific index of an array.
To search inside an array you can simply use an Iteration method ( forEach/ map ) and, inside that use JavaScript String search method Thanks for contributing an answer to Stack Overflow!
JavaScript String search() Method ... The search() method searches a string for a specified value, and returns the position of the match. The search value can be string or a regular expression. This method returns -1 if no match is found. Read more about regular expressions in our RegExp Tutorial and our RegExp Object Reference.
Definition and Usage. The search() method searches a string for a specified value, and returns the position of the match. The search value can be string or a regular expression. This method returns -1 if no match is found.
The search value can be a string or a regular expression. Required. A string or a regular expression. The position of the first match. -1 if no match. search () is an ES1 feature (JavaScript 1997).
You could filter elements which match in a new array and just return the length of this new array
var j_arry = ["class:1","division:a","class:5","class:3","division:b","division:c","division:d","class:10"];
var res = j_arry.filter(x => x.includes("class"));
var key = res.map(x => x.split(":")[1]);
console.log("Class coming " + res.length + " , at key " + key.join(","));
console.log("new array = ", res);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With