Sunday, 8 January 2017

How do I search a string in JavaScript array using jQuery?





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:




  1. Class coming 4 times, at key 0, 2, 3, and 7


  2. I want to make a separate array of class only, that is,




    new_array = ["class:1", "class:2", "class:3", "class:10"];

  3. 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.


Answer



Use Array.prototype.filter to filter out the elements of the array that contains the string class - see demo below:






var j_array =["class:1","division:a","class:5","class:3","division:b","division:c","division:d","class:10"];

var result = j_array.filter(function(e){
return e.indexOf('class')!==-1;
});

console.log(result);






EDIT:



To get the list of indexes too, you can try this:





var j_array =["class:1","division:a","class:5","class:3","division:b","division:c","division:d","class:10"];


var filteredIndices = []

var filtered = j_array.filter(function(e,i){
if(e.indexOf('class')!==-1) {
filteredIndices.push(i);
return true;
} else {
return false;
}
});


console.log(filtered);
console.log(filteredIndices);

// Nth class value
console.log(filtered[2]); // this prints the 3rd one

.as-console-wrapper{top:0;max-height:100%!important;}





No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...