简体   繁体   中英

JavaScript array manipulation to delete odd array elements

I need help; I have an array like this:

myarray = ["nonsense","goodpart","nonsense2","goodpar2t","nonsense3","goodpart3",]

I need to delete all "nonsense" part from array.

Nonsense always have an even index.

I'd suggest, on the basis that 'nonsense' words are always (as stated in the question) the 'even' elements:

 var myarray = ["nonsense", "goodpart", "nonsense2", "goodpar2t", "nonsense3", "goodpart3"], filtered = myarray.filter(function(el, index) { // normally even numbers have the feature that number % 2 === 0; // JavaScript is, however, zero-based, so want those elements with a modulo of 1: return index % 2 === 1; }); console.log(filtered); // ["goodpart", "goodpar2t", "goodpart3"] 

If, however, you wanted to filter by the array-elements themselves, to remove all words that contain the word 'nonsense':

 var myarray = ["nonsense", "goodpart", "nonsense2", "goodpar2t", "nonsense3", "goodpart3"], filtered = myarray.filter(function(el) { // an indexOf() equal to -1 means the passed-in string was not found: return el.indexOf('nonsense') === -1; }); console.log(filtered); // ["goodpart", "goodpar2t", "goodpart3"] 

Or to find, and keep, only those words that begin with 'good' :

 var myarray = ["nonsense", "goodpart", "nonsense2", "goodpar2t", "nonsense3", "goodpart3"], filtered = myarray.filter(function(el) { // here we test the word ('el') against the regular expression, // ^good meaning a string of 'good' that appears at the beginning of the // string: return (/^good/).test(el); }); console.log(filtered); // ["goodpart", "goodpar2t", "goodpart3"] 

References:

This is just a slight variation to @DavidThomas's great answer (+1). This will be helpful in case you decide to exclude array members by value ( nonsense ) instead of by position ( odd ):

var myarray = ["nonsense", "goodpart", "nonsense2", "goodpar2t", "nonsense3", "goodpart3"],
    filtered = myarray.filter(function(el) {
        //return only values that do not contain 'nonsense'
        return el.indexOf('nonsense') === -1;
    });

 var myarray = ["nonsense", "goodpart", "nonsense2", "goodpar2t", "nonsense3", "goodpart3"], filtered = myarray.filter(function(el) { //return only values that do not contain 'nonsense' return el.indexOf('nonsense') === -1; }); //output result $('pre.out').text( JSON.stringify( filtered ) ); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <pre class="out"></div> 

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