Jak usunąć element z tablicy według wartości?

Czy istnieje metoda do usunięcia elementu z tablicy JavaScript?

Podano tablicę:

var ary = ['three', 'seven', 'eleven'];

Chciałbym zrobić coś takiego:

removeItem('seven', ary);

Przyjrzałem się splice() ale to usuwa tylko przez numer pozycji, podczas gdy potrzebuję czegoś, aby usunąć element według jego wartości.

Author: Paul Roub, 2010-10-17

30 answers

Może to być funkcja globalna lub metoda obiektu niestandardowego, jeśli nie możesz dodawać do natywnych prototypów. Usuwa wszystkie elementy z tablicy, które pasują do któregokolwiek z argumentów.

Array.prototype.remove = function() {
    var what, a = arguments, L = a.length, ax;
    while (L && this.length) {
        what = a[--L];
        while ((ax = this.indexOf(what)) !== -1) {
            this.splice(ax, 1);
        }
    }
    return this;
};

var ary = ['three', 'seven', 'eleven'];

ary.remove('seven');

/*  returned value: (Array)
three,eleven
*/

To make it a global-

function removeA(arr) {
    var what, a = arguments, L = a.length, ax;
    while (L > 1 && arr.length) {
        what = a[--L];
        while ((ax= arr.indexOf(what)) !== -1) {
            arr.splice(ax, 1);
        }
    }
    return arr;
}
var ary = ['three', 'seven', 'eleven'];
removeA(ary, 'seven');


/*  returned value: (Array)
three,eleven
*/

I dbać o IE8 i poniżej -

if(!Array.prototype.indexOf) {
    Array.prototype.indexOf = function(what, i) {
        i = i || 0;
        var L = this.length;
        while (i < L) {
            if(this[i] === what) return i;
            ++i;
        }
        return -1;
    };
}
 394
Author: kennebec,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-11-21 05:38:42

Możesz użyć indexOf metoda Tak:

var index = array.indexOf(item);
if (index !== -1) array.splice(index, 1);

Uwaga: musisz go schimować dla IE8 i poniżej

var array = [1,2,3,4]
var item = 3

var index = array.indexOf(item);
if (index !== -1) array.splice(index, 1);

console.log(array)
 1203
Author: SLaks,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-02-08 18:54:26

Jednolinijkowy to zrobi,

var ary = ['three', 'seven', 'eleven'];

// Remove item 'seven' from array
var filteredAry = ary.filter(function(e) { return e !== 'seven' })
//=> ["three", "eleven"]

// In ECMA6 (arrow function syntax):
var filteredAry = ary.filter(e => e !== 'seven')

Wykorzystuje to funkcję filter w JS. Jest obsługiwany w IE9 i nowszych wersjach.

Co robi (z linku doc)

Filter() wywołuje dostarczoną funkcję wywołania zwrotnego raz dla każdego elementu w tablicy i konstruuje nową tablicę wszystkich wartości, dla których callback Zwraca wartość wymuszającą true. wywołanie zwrotne jest wywoływane tylko dla indeksów tablicy, które mają przypisane wartości; nie jest wywoływane dla indeksów, które mają zostały usunięte lub które nigdy nie zostały przypisane wartości. Elementy tablicy, które nie przeszły testu wywołania zwrotnego, są po prostu pomijane i nie są dołączane do nowej tablicy.

Więc zasadniczo jest to to samo, co wszystkie inne for (var key in ary) { ... } rozwiązania, z tym, że for in construct jest obsługiwany od IE6.

Zasadniczo filtr jest wygodną metodą, która wygląda o wiele ładniej (i jest łańcuchowa) w przeciwieństwie do for in construct (AFAIK).

 263
Author: John Williams,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-08-26 12:30:00

Możesz użyć podkreślenia.js . To naprawdę ułatwia sprawę.

Na przykład:

var result = _.without(['three','seven','eleven'], 'seven');

I result będą ['three','eleven'].

W Twoim przypadku kod, który będziesz musiał napisać to:

ary = _.without(ary, 'seven')

Zmniejsza kod, który piszesz.

 126
Author: vatsal,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-05-31 05:15:40

Zobacz też:

for(var i in array){
    if(array[i]=='seven'){
        array.splice(i,1);
        break;
    }
}

I w funkcji:

function removeItem(array, item){
    for(var i in array){
        if(array[i]==item){
            array.splice(i,1);
            break;
        }
    }
}

removeItem(array, 'seven');
 45
Author: gadlol,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-01-23 14:24:25

Oto wersja, która używa funkcji jQuery inArray :

var index = $.inArray(item, array);
if (index != -1) {
    array.splice(index, 1);
}
 34
Author: CorayThan,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-03-23 19:46:06
var index = array.indexOf('item');

if(index!=-1){

   array.splice(index, 1);
}
 25
Author: Kld,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-11-13 13:49:05

Możesz to zrobić na dwa sposoby:

var arr = ["1","2","3","4"] // we wanna delete number "3"

Pierwszy:

arr.indexOf('3') !== -1 && arr.splice(arr.indexOf('3'), 1)

Drugi (ES6):

arr = arr.filter(e => e !== '3')
 19
Author: AngelHotxxx,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-07-24 13:10:17

What You ' re after is filter

Https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter

To pozwoli Ci wykonać następujące czynności:

var ary = ['three', 'seven', 'eleven'];
var aryWithoutSeven = ary.filter(function(value) { return value != 'seven' });
console.log(aryWithoutSeven); // returns ['three', 'eleven']

Zostało to również odnotowane w tym wątku gdzie indziej: https://stackoverflow.com/a/20827100/293492

 15
Author: Lotus,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-05-23 12:18:24

Ponieważ nie ma ładnej, oto prosta i wielokrotnego użytku funkcja ES6.

const removeArrayItem = (arr, itemToRemove) => {
  return arr.filter(item => item !== itemToRemove)
}

Użycie:

const items = ['orange', 'purple', 'orange', 'brown', 'red', 'orange']
removeArrayItem(items, 'orange')
 9
Author: Shakespeare,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-07-21 16:16:27

Bardzo czystym rozwiązaniem działającym we wszystkich przeglądarkach i bez żadnego frameworka jest przypisanie nowej tablicy i po prostu zwrócenie jej bez elementu, który chcesz usunąć:

/**
 * @param {Array} array the original array with all items
 * @param {any} item the time you want to remove
 * @returns {Array} a new Array without the item
 */
var removeItemFromArray = function(array, item){
  /* assign a empty array */
  var tmp = [];
  /* loop over all array items */
  for(var index in array){
    if(array[index] !== item){
      /* push to temporary array if not like item */
      tmp.push(array[index]);
    }
  }
  /* return the temporary array */
  return tmp;
}
 7
Author: mtizziani,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-05-19 05:44:31

Jeśli masz unikalne wartości w tablicy i kolejność nie ma znaczenia, możesz użyć Set , i ma delete :

var mySet = new Set(['foo']);
mySet.delete('foo'); // Returns true.  Successfully removed.
mySet.has('foo');    // Returns false. The "foo" element is no longer present.
 7
Author: greene,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-05-03 21:04:51

Usunięcie wszystkich pasujących elementów z tablicy (a nie tylko pierwszego as wydaje się być najczęstszą odpowiedzią tutaj):

while ($.inArray(item, array) > -1) {
    array.splice( $.inArray(item, array), 1 );
}

Użyłem jQuery do podnoszenia ciężarów, ale masz pomysł, jeśli chcesz przejść natywny.

 6
Author: Jason,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-01-22 17:04:50

indexOf jest opcją, ale jej implementacja polega w zasadzie na przeszukiwaniu całej tablicy pod kątem wartości, więc czas wykonania rośnie wraz z rozmiarem tablicy. (tak jest chyba w każdej przeglądarce, sprawdziłem tylko Firefoksa).

Nie mam IE6 do sprawdzenia, ale nazwałbym to bezpiecznym zakładem, że możesz sprawdzić co najmniej milion elementów tablicy na sekundę w ten sposób na prawie każdej maszynie klienckiej. Jeśli [rozmiar tablicy]*[wyszukiwanie na sekundę] może wzrosnąć powyżej miliona, powinieneś rozważyć inną wdrożenie.

W zasadzie można użyć obiektu do utworzenia indeksu dla tablicy, w ten sposób:

var index={'three':0, 'seven':1, 'eleven':2};

Każde rozsądne środowisko JavaScript stworzy indeks przeszukiwalny dla takich obiektów, dzięki czemu można szybko przetłumaczyć klucz na wartość, bez względu na to, ile właściwości ma obiekt.

Jest to tylko podstawowa metoda, w zależności od potrzeb można połączyć kilka obiektów i / lub tablic, aby te same dane szybko przeszukiwać dla różnych właściwości. Jeśli określisz swój dokładne potrzeby mogę zasugerować bardziej szczegółową strukturę danych.

 4
Author: aaaaaaaaaaaa,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2010-10-17 18:32:22

Naprawdę, nie rozumiem, dlaczego nie można tego rozwiązać

arr = arr.filter(value => value !== 'seven');

A może chcesz użyć vanilla JS

arr = arr.filter(function(value) { return value !== 'seven' });
 4
Author: rbenvenuto,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-07-13 01:18:08

Sztuką jest przechodzenie przez tablicę od końca do początku, aby nie zepsuć indeksów podczas usuwania elementów.

var deleteMe = function( arr, me ){
   var i = arr.length;
   while( i-- ) if(arr[i] === me ) arr.splice(i,1);
}

var arr = ["orange","red","black", "orange", "white" , "orange" ];

deleteMe( arr , "orange");

Arr jest teraz ["Czerwony", "Czarny","biały"]

 3
Author: chaoticflow,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-03-17 17:43:15

ES6 way.

let commentsWithoutDeletedArray = commentsArray.filter( (comment) => !(comment.Id === commentId));
 3
Author: Oliver Dixon,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-05-29 14:34:53

Usuwanie nieniszczące:

function removeArrayValue(array, value)
{
    var thisArray = array.slice(0); // copy the array so method is non-destructive

    var idx = thisArray.indexOf(value); // initialise idx

    while(idx != -1)
    {
        thisArray.splice(idx, 1); // chop out element at idx

        idx = thisArray.indexOf(value); // look for next ocurrence of 'value'
    }

    return thisArray;
}
 2
Author: Randhir Rawatlal,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-06-25 12:17:37

Proszę nie używać wariantu z delete - robi dziurę w tablicy, ponieważ nie indeksuje ponownie elementów po usuniętym elemencie.

> Array.prototype.remove=function(v){
...     delete this[this.indexOf(v)]
... };
[Function]
> var myarray=["3","24","55","2"];
undefined
> myarray.remove("55");
undefined
> myarray
[ '3', '24', , '2' ]
 1
Author: Ilya Sher,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-05-05 16:56:03

Użyłem najczęściej głosowanej opcji i stworzyłem funkcję, która wyczyściłaby jedną tablicę słów za pomocą innej tablicy niechcianych słów:

function cleanArrayOfSpecificTerms(array,unwantedTermsArray) {
  $.each(unwantedTermsArray, function( index, value ) {
    var index = array.indexOf(value);
    if (index > -1) {
      array.splice(index, 1);        
    }
  });
  return array;
}

Aby użyć, wykonaj następujące czynności:

var notInclude = ['Not','No','First','Last','Prior','Next', 'dogs','cats'];
var splitTerms = ["call", "log", "dogs", "cats", "topic", "change", "pricing"];

cleanArrayOfSpecificTerms(splitTerms,notInclude)
 1
Author: maudulus,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-02-10 16:06:19
function removeFrmArr(array, element) {
  return array.filter(e => e !== element);
};
var exampleArray = [1,2,3,4,5];
removeFrmArr(a, 3);
// return value like this
//[1, 2, 4, 5]
 1
Author: Subhojit Mondal,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-02-13 07:27:50

Możesz użyć without lub pull z Lodash :

const _ = require('lodash');
_.without([1, 2, 3, 2], 2); // -> [1, 3]
 1
Author: sakovias,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-03-18 15:20:32
let arr = [5, 15, 25, 30, 35];
console.log(arr); //result [5, 15, 25, 30, 35]
let index = arr.indexOf(30);

if (index > -1) {
   arr.splice(index, 1);
}
console.log(arr); //result [5, 15, 25, 35]
 1
Author: Asif vora,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-04-18 09:02:21
var remove = function(array, value) {
    var index = null;

    while ((index = array.indexOf(value)) !== -1)
        array.splice(index, 1);

    return array;
};
 0
Author: Alexander Abashkin,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-01-13 21:51:46

Próbowałem użyć metody funkcji z jbaron powyżej, ale okazało się, że muszę zachować oryginalną tablicę nienaruszoną do późniejszego użycia i utworzyć nową tablicę w ten sposób:

var newArray = referenceArray;

Najwyraźniej tworzy przez odniesienie zamiast wartości, ponieważ gdy usunąłem element z newArray, referenceArray również go usunął. Postanowiłem więc za każdym razem utworzyć nową tablicę w ten sposób:

function newArrRemoveItem(array, item, newArray){
    for(var i = 0; i < array.length; i++) {
        if(array[i]!=item){
            newArray.push(array[i]);
        }
    }
}

Potem używam go tak w innej funkcji:

var vesselID = record.get('VesselID');
var otherVessels = new Array();
newArrRemoveItem(vesselArr,vesselID,otherVessels);

Teraz statek pozostaje nienaruszony podczas gdy za każdym razem wykonuję powyższy kod tablica otherVessels zawiera wszystkie oprócz najnowszego elementu vesselID.

 0
Author: Robert,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-05-29 18:18:46

Coffeescript+jQuery variant:

arrayRemoveItemByValue = (arr,value) ->
  r=$.inArray(value, arr)
  unless r==-1
    arr.splice(r,1)
  # return
  arr

console.log arrayRemoveItemByValue(['2','1','3'],'3')

Usuwa tylko jeden, nie wszystkie.

 0
Author: Igor Teterin,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-09-13 03:02:00
//This function allows remove even array from array
var removeFromArr = function(arr, elem) { 
    var i, len = arr.length, new_arr = [],
    sort_fn = function (a, b) { return a - b; };
    for (i = 0; i < len; i += 1) {
        if (typeof elem === 'object' && typeof arr[i] === 'object') {
            if (arr[i].toString() === elem.toString()) {
                continue;
            } else {                    
                if (arr[i].sort(sort_fn).toString() === elem.sort(sort_fn).toString()) {
                    continue;
                }
            }
        }
        if (arr[i] !== elem) {
            new_arr.push(arr[i]);
        }
    }
    return new_arr;
}

Przykład użycia

var arr = [1, '2', [1 , 1] , 'abc', 1, '1', 1];
removeFromArr(arr, 1);
//["2", [1, 1], "abc", "1"]

var arr = [[1, 2] , 2, 'a', [2, 1], [1, 1, 2]];
removeFromArr(arr, [1,2]);
//[2, "a", [1, 1, 2]]
 0
Author: yesnik,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-01-29 03:40:56

Inna odmiana:

if (!Array.prototype.removeArr) {
    Array.prototype.removeArr = function(arr) {
        if(!Array.isArray(arr)) arr=[arr];//let's be nice to people who put a non-array value here.. that could be me!
        var that = this;
        if(arr.length){
            var i=0;
            while(i<that.length){
                if(arr.indexOf(that[i])>-1){
                    that.splice(i,1);
                }else i++;
            }
        }
        return that;
    }
}

Jest to funkcja indexOf () ponownie wewnątrz pętli, ale przy założeniu, że tablica do usunięcia jest mała w stosunku do tablicy do czyszczenia; każde usunięcie skraca pętlę while.

 0
Author: dkloke,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-04-06 17:30:05

//edytowane dzięki MarcoCI za poradę

Spróbuj tego:

function wantDelete(item, arr){
  for (var i=0;i<arr.length;i++){
    if (arr[i]==item){
      arr.splice(i,1); //this delete from the "i" index in the array to the "1" length
      break;
    }
  }  
}
var goodGuys=wantDelete('bush', ['obama', 'bush', 'clinton']); //['obama', 'clinton']

Mam nadzieję, że to ci pomoże

 0
Author: julian,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-03-02 00:15:36

W funkcji globalnej nie możemy przekazać bezpośrednio wartości niestandardowej, ale istnieje wiele sposobów, jak poniżej

 var ary = ['three', 'seven', 'eleven'];
 var index = ary.indexOf(item);//item: the value which you want to remove

 //Method 1
 ary.splice(index,1);

 //Method 2
 delete ary[index]; //in this method the deleted element will be undefined
 0
Author: Srikrushna Pal,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-08-19 18:54:36