anson920520 anson920520 - 6 months ago 7
Javascript Question

$.inArray() : check if array value has "+" inside

I have an array like below created by jQuery:

var arr = ["a+ab","g+cc","bc","dk"]


I'd like to do a checker in order to loop through the whole array and return only the array value with
+
.

After handling, the result should be:

var arr2 = ["a+ab","g+cc"]


Should I do it by using
$.inArray()
?

If I want to get the value with + sign I do:

var arr = ["a+ab", "g+cc", "bc", "dk"];

var res = arr.filter(function(v) {
return v.indexOf('+') > -1;
})

console.log(res);


What if I want the the value without + sign?

var arr = ["a+ab", "g+cc", "bc", "dk"];

var res = arr.filter(function(v) {
return v.indexOf('+') > 1;
})

console.log(res);


Is the above correct?

Update:

function keywordArray() {
var keywordArrayRow = [];

$(".tag-container .tag-item .word").each(function (i, e) {
keywordArrayRow.push($(e).text());
});

var keywordArray = keywordArrayRow.filter(function(v) {
return v.indexOf('+') == -1;
})
return keywordArrayRow;
}
function AndkeywordArray() {
var AndkeywordArrayRow = [];

$(".tag-container .tag-item .word").each(function (i, e) {
AndkeywordArrayRow.push($(e).text());
});

var AndkeywordArray = AndkeywordArrayRow.filter(function(v) {
return v.indexOf(' + ') > -1;
})

return AndkeywordArray;
}

Answer

I don't think $.inArray() can be use here. $.inArray() is used to search for a specified value within an array and return its index (or -1 if not found).


For filtering an array use native JavaScript filter() method

var arr = ["a+ab", "g+cc", "bc", "dk"];

var res = arr.filter(function(v) {
  return v.indexOf('+') > -1;
})

console.log(res);


UPDATE 1 :

In case if you want element which are not contains + symbol then use following code.

var arr = ["a+ab", "g+cc", "bc", "dk"];

var res = arr.filter(function(v) {
  return v.indexOf('+') == -1;
})

console.log(res);

UPDATE 2 :

Inside keywordArray function returning the original array instead of filtered array.

function keywordArray() {
  var keywordArrayRow = [];

  $(".tag-container .tag-item .word").each(function(i, e) {
    keywordArrayRow.push($(e).text());
  });

  var keywordArray = keywordArrayRow.filter(function(v) {
    return v.indexOf('+') == -1;
  })
  return keywordArray;
  //---------^------ change here
}