jquery - JavaScript array manipulation to delete odd array elements -
i need help; have array this:
myarray = ["nonsense","goodpart","nonsense2","goodpar2t","nonsense3","goodpart3",]
i need delete "nonsense" part array.
nonsense have index.
i'd suggest, on basis 'nonsense' words (as stated in question) 'even' elements:
var myarray = ["nonsense", "goodpart", "nonsense2", "goodpar2t", "nonsense3", "goodpart3"], filtered = myarray.filter(function(el, index) { // numbers have feature number % 2 === 0; // javascript is, however, zero-based, want elements modulo of 1: return index % 2 === 1; }); console.log(filtered); // ["goodpart", "goodpar2t", "goodpart3"]
if, however, wanted filter array-elements themselves, remove words contain word 'nonsense':
var myarray = ["nonsense", "goodpart", "nonsense2", "goodpar2t", "nonsense3", "goodpart3"], filtered = myarray.filter(function(el) { // indexof() equal -1 means passed-in string not found: return el.indexof('nonsense') === -1; }); console.log(filtered); // ["goodpart", "goodpar2t", "goodpart3"]
or find, , keep, words begin 'good'
:
var myarray = ["nonsense", "goodpart", "nonsense2", "goodpar2t", "nonsense3", "goodpart3"], filtered = myarray.filter(function(el) { // here test word ('el') against regular expression, // ^good meaning string of 'good' appears @ beginning of // string: return (/^good/).test(el); }); console.log(filtered); // ["goodpart", "goodpar2t", "goodpart3"]
references:
Comments
Post a Comment