简体   繁体   中英

how to filter an array with index of condition in javascript

Having less background of any coding, am trying to acheive a filtered array from an existing array with indexof condition in javascript.

My code:

function CheckIfexists(element) {
  return (element.indexOf(formInput) > -1);
}
var filtered = data.filter(CheckIfexists);
window.alert(filtered[1] + " " + filtered[2] + " " + filtered[3]);

above code is not working

addl info:

forminput is input taken from form feild.

var formInput = document.getElementById("textReader").value;

data array i got by...

var data = oRequest.responseText.split("\r\n");

another way i tried is..

function CheckIfexists(formInput) {
   for (var i = 0; i < data.length; i += 1) {
       if (data[i].indexOf(formInput) > -1) {
           return false;
       }
   } 
   return true;
}

var filtered = data.filter(CheckIfexists);
window.alert(filtered[1] + " " + filtered[2] + " " + filtered[3]);

the above code is also not working..


donot doubt about data array and forminput beacuse i checked each element with code, al

for(var i=0; i<data.length; i++) {  
    if (data[i] === formInput) {
        alert("You want to retrieve report?");
        didntfind = false;
        break;
    } 
}

     if (didntfind) alert("sorry. part not found");

and i got the ones matching and not matching. Addl note: data array has part names, forminput may not be exactly same as element in data array, it can also be partial.. My struggle is to get the filtered ones in new array.

Function CheckIfexists will be called on every element in array. Read and run this code for better understanding:

var data = [1,2,3,4,10];
console.log(data.filter(function (item) { return item > 3; }));

I can see what you trying to do. I think, you need to write something like that:

var formInput = document.getElementById("textReader").value;
var data = oRequest.responseText.split("\r\n");

function CheckIfExists(element) {
  return (element === formInput);
};

var filtered = data.filter(CheckIfexists);

And be aware when cheking equality of elements ("1" !== 1, for example) in javascript.

var newArray = [];
for(var i=0;i<data.length;i++) {
    var item = data[i];
    if(item.indexOf(formInput1) > -1) {
        newArray.push(item);
    }
});

I got it.. kind of above code is working for me... Thanks again..

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM