简体   繁体   中英

Javascript Remove specific only needed n-th elements of array

For example i have an array

var fruits = ["Banana", "Orange", "Apple", "Mango", "App", "Man"];

The code

fruits.splice(2, 2);

Return me output

Banana,Orange,App,Man

But how to return only 1,3,4 elements from array without looping?

So i will get

Orange,Mango,App

I imaging must be something like that

fruits.splice( fruits.indexOf(Orange,Mango,App), 1 );  

You can use filter to filter out certain items:

fruits = fruits.filter(function (e, i) {
    return i === 1 || i === 3 || i === 4;
});

Or if you want to keep certain items based on their identity (which seems to be what you're trying to do at the end of your question):

fruits = fruits.filter(function (e) {
    return e === "Orange" || e === "Mango" || e === "App";
});

The same as JLRishe 's answer but with the addition that you can pass in a list of those elements that you want to keep:

 var fruits = ["Banana", "Orange", "Apple", "Mango", "App", "Man"]; var list = 'Orange, Mango, App'; alert(strip(fruits, list)); // ["Orange", "Mango", "App"] function strip(arr, list) { list = list.split(', '); return arr.filter(function (el) { return list.indexOf(el) > -1; }); } 

You may combine slice and splice methods:

 var fruits = ["Banana", "Orange", "Apple", "Mango", "App", "Man"]; 
 fruits.splice(2,1);
 var x = fruits.slice(1,4); 
 x;

Explanation:

  • splice deletes 1 element starting at index 2 ( ie. "Apple" ).
  • slice extracts 3 elements starting at index 1 ( ie. "Orange", "Apple", "Mango", "App"; remember that at this time, the array no longer contains "Apple").

Variation (non-destructive):

var fruits = ["Banana", "Orange", "Apple", "Mango", "App", "Man"]; 
var x = fruits.slice(1,2).concat(fruits.slice(3,5));
x;

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