Как удалить определенный элемент из массива в JavaScript?

У меня есть массив целых чисел, и я использую .push() метод для добавления элементов к нему.

Есть ли простой способ удалить определенный элемент из массива? Эквивалент чего-то вроде array.remove(int);,

Я должен использовать основной JavaScript - не допускается никаких структур.

159 ответов

var array = [2, 5, 9];
array.splice(array.findIndex(x => x==5), 1);

Используя Array.findindex, мы можем уменьшить количество строк кода.

developer.mozilla.org

Опубликовать мой код, который удаляет элемент массива на месте, а также уменьшить длину массива.

function removeElement(idx, arr) {
    // check the index value
    if (idx < 0 || idx >= arr.length) {
        return;
    }
    // shift the elements
    for (var i = idx; i > 0; --i) {
        arr[i] = arr[i - 1];
    }
    // remove the first element in array
    arr.shift();
}
       (function removeFromArrayPolyfill() {
      if (window.Array.prototype.remove) return;
    
      Array.prototype.remove = function (value) {
        if (!this.length || !value) return;
    
        const indexOfValue = this.indexOf(value);
    
        if (indexOfValue >= 0) {
          this.splice(indexOfValue, 1);
        }
      };
    })();
    
    // testing polyfill
    const nums = [10, 20, 30];
    nums.remove(20);
    console.log(nums);//[10,30]

Я нашел это сообщение в блоге, в котором показаны девять способов сделать это:

9 способов удалить элементы из массива JavaScript - плюс как безопасно очистить массивы JavaScript

Я предпочитаю использовать filter():

var filtered_arr = arr.filter(function(ele){
   return ele != value;
})

Удаление значения с помощью индекса и сплайсинга!

function removeArrValue(arr,value) {
    var index = arr.indexOf(value);
    if (index > -1) {
        arr.splice(index, 1);
    }
    return arr;
}

Лучший способ удалить элемент из массива — использовать метод пользовательского фильтра. .filter() возвращает новый массив без отфильтрованного элемента.

      items = items.filter(e => e.id !== item.id);

Этот метод .filter() сопоставляется с полным массивом, и когда я возвращаю истинное условие, он помещает текущий элемент в отфильтрованный массив. подробнее о фильтре ЗДЕСЬ

Мне нравится эта версия сращивания, удалив элемент по его значению, используя $.inArray:

$(document).ready(function(){
    var arr = ["C#","Ruby","PHP","C","C++"];
    var itemtoRemove = "PHP";
    arr.splice($.inArray(itemtoRemove, arr),1);
});

Удалите одно значение, используя свободное сравнение, без изменения исходного массива, ES6

/**
 * Removes one instance of `value` from `array`, without mutating the original array. Uses loose comparison.
 * 
 * @param {Array} array Array to remove value from
 * @param {*} value Value to remove
 * @returns {Array} Array with `value` removed
 */
export function arrayRemove(array, value) {
    for(let i=0; i<array.length; ++i) {
        if(array[i] == value) {
            let copy = [...array];
            copy.splice(i, 1);
            return copy;
        }
    }
    return array;
}

для удаления только первого из веков, а не всех веков

      ages.splice(ages.indexOf(34), 1);

для удаления всех возрастов 34

      ages = ages.filter(a => a != 34);

Большинство ответов здесь дают решение с использованием -

  1. indexOf и splice
  2. удалять
  3. фильтр
  4. регулярный for loop

Хотя все решения должны работать с этими методами, я подумал, что мы могли бы использовать манипуляции со строками.

Обратите внимание на это решение -

  1. Это оставит дыры в данных (их можно удалить с помощью дополнительного фильтра)
  2. Это решение работает не только с примитивными значениями поиска, но и с объектами.

Хитрость в том, чтобы -

  1. stringify набор входных данных и значение поиска
  2. заменить значение поиска во входном наборе данных пустой строкой
  3. возвращение split данные о разделителе ,.
    remove = (input, value) => {
        const stringVal = JSON.stringify(value);
        const result = JSON.stringify(input)

        return result.replace(stringVal, "").split(",");
    }

Здесь создается JSFiddle с тестами на объекты и числа - https://jsfiddle.net/4t7zhkce/33/

Проверить remove метод в скрипке.

По моему решению вы можете удалить один или несколько элементов в массиве благодаря чистому JavaScript. Нет необходимости в другой библиотеке JavaScript.

var myArray = [1,2,3,4,5]; // First array

var removeItem = function(array,value) {  // My clear function
    if(Array.isArray(value)) {  // For multi remove
        for(var i = array.length - 1; i >= 0; i--) {
            for(var j = value.length - 1; j >= 0; j--) {
                if(array[i] === value[j]) {
                    array.splice(i, 1);
                };
            }
        }
    }
    else { // For single remove
        for(var i = array.length - 1; i >= 0; i--) {
            if(array[i] === value) {
                array.splice(i, 1);
            }
        }
    }
}

removeItem(myArray,[1,4]); // myArray will be [2,3,5]

Я сделал довольно эффективное расширение базового массива JavaScript:

Array.prototype.drop = function(k) {
  var valueIndex = this.indexOf(k);
  while(valueIndex > -1) {
    this.removeAt(valueIndex);
    valueIndex = this.indexOf(k);
  }
};

Не на месте решение

arr.slice(0,i).concat(arr.slice(i+1));

let arr = [10, 20, 30, 40, 50]

let i = 2 ; // position to remove (starting from 0)
let r = arr.slice(0,i).concat(arr.slice(i+1));

console.log(r);

Вы можете создать индекс с примером всех аксессоров:

<div >
</div>

function getIndex($id){
  return (
    this.removeIndex($id)
    alert("This element was removed")
  )
}


function removeIndex(){
   const index = $id;
   this.accesor.id.splice(index.id) // You can use splice for slice index on
                                    // accessor id and return with message
}
<div>
    <fromList>
        <ul>
            {...this.array.map( accesors => {
                <li type="hidden"></li>
                <li>{...accesors}</li>
            })

            }
        </ul>
    </fromList>

    <form id="form" method="post">
        <input  id="{this.accesors.id}">
        <input type="submit" callbackforApplySend...getIndex({this.accesors.id}) name="sendendform" value="removeIndex" >
    </form>
</div>

Ванильный JavaScript (ES5.1) - на месте редакции

Поддержка браузера: Internet Explorer 9 или более поздняя версия ( подробная поддержка браузера)

/**
 * Removes all occurences of the item from the array.
 *
 * Modifies the array “in place”, i.e. the array passed as an argument
 * is modified as opposed to creating a new array. Also returns the modified
 * array for your convenience.
 */
function removeInPlace(array, item) {
    var foundIndex, fromIndex;

    // Look for the item (the item can have multiple indices)
    fromIndex = array.length - 1;
    foundIndex = array.lastIndexOf(item, fromIndex);

    while (foundIndex !== -1) {
        // Remove the item (in place)
        array.splice(foundIndex, 1);

        // Bookkeeping
        fromIndex = foundIndex - 1;
        foundIndex = array.lastIndexOf(item, fromIndex);
    }

    // Return the modified array
    return array;
}

Vanilla JavaScript (ES5.1) - неизменная версия

Поддержка браузера: То же, что и ванильный JavaScript на месте издания

/**
 * Removes all occurences of the item from the array.
 *
 * Returns a new array with all the items of the original array except
 * the specified item.
 */
function remove(array, item) {
    var arrayCopy;

    arrayCopy = array.slice();

    return removeInPlace(arrayCopy, item);
}

Vanilla ES6 - неизменное издание

Поддержка браузера: Chrome 46, Edge 12, Firefox 16, Opera 37, Safari 8 ( подробная поддержка браузера)

/**
 * Removes all occurences of the item from the array.
 *
 * Returns a new array with all the items of the original array except
 * the specified item.
 */
function remove(array, item) {
    // Copy the array
    array = [...array];

    // Look for the item (the item can have multiple indices)
    let fromIndex = array.length - 1;
    let foundIndex = array.lastIndexOf(item, fromIndex);

    while (foundIndex !== -1) {
        // Remove the item by generating a new array without it
        array = [
            ...array.slice(0, foundIndex),
            ...array.slice(foundIndex + 1),
        ];

        // Bookkeeping
        fromIndex = foundIndex - 1;
        foundIndex = array.lastIndexOf(item, fromIndex)
    }

    // Return the new array
    return array;
}

Удалить элемент из последнего

arrName.pop();

удалить элемент из первого

arrName.shift();

удалить из середины

arrName.splice(starting index,number of element you wnt to delete);

Ex: arrName.splice(1,1);

удалить один элемент из последнего

arrName.splice(-1);

Удалить используя индексный номер массива

 delete arrName[1];

Используйте jQuery.grep ():

var y = [1, 2, 3, 9, 4]
var removeItem = 9;

y = jQuery.grep(y, function(value) {
  return value != removeItem;
});
console.log(y)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>

Я сделал функцию

function pop(valuetoremove, myarray) {
var indexofmyvalue = myarray.indexOf(valuetoremove);
myarray.splice(indexofmyvalue, 1);
}

И использовал вот так.

pop(valuetoremove,myarray);

Ура!

Эта функция удаляет элемент из массива с определенной позиции.

array.remove(position);

Если массив содержит повторяющиеся значения, и вы хотите удалить все вхождения своей цели, тогда это путь...

let data = [2, 5, 9, 2, 8, 5, 9, 5];
let target = 5;
data = data.filter(da => da !== target);

Примечание: - фильтр не меняет исходный массив; вместо этого он создает новый массив.

Поэтому повторное назначение важно.

Это привело к другой проблеме. Вы не можете сделать переменнуюconst. Должен бытьlet или var.

Хотя большинство ответов, приведенных выше, отвечают на вопрос, недостаточно ясно, почему slice() Метод не был использован. Да, filter() соответствует критериям неизменности, но как насчет выполнения следующего более короткого эквивалента:

const myArray = [1,2,3,4];

А теперь давайте скажем, что мы должны удалить второй элемент из массива, мы можем просто сделать:const newArray = myArray.slice(0,1).concat(myArray.slice(2,4));// [1,3,4]

Этот способ удаления элемента из массива настоятельно рекомендуется сегодня в сообществе из-за его простой и неизменной природы. В общем, следует избегать методов, вызывающих мутацию. Например, вам рекомендуется заменить push() с concat() а также splice() с slice()

Ты можешь использовать splice для удаления объектов или значений из массива.

Рассмотрим массив длины 5, со значениями 10,20,30,40,50, и я хочу удалить значение 30 от него.

var array = [10,20,30,40,50];
if (array.indexOf(30) > -1) {
   array.splice(array.indexOf(30), 1);
}
console.log(array); // [10,20,40,50]

Вы можете с помощью стандартного прото из JavaScript и определил эту функцию. Например.

  1. Используя indexOf, можно найти определенный индекс числа из массива

    • используя splice, можно удалить определенный индекс из массива.

В вашем вопросе не указано, является ли порядок или отдельные значения обязательными.

Если вы не заботитесь о заказе и не будете иметь одно и то же значение в контейнере более одного раза, используйте Set. Это будет намного быстрее и кратче.

var aSet = new Set();

aSet.add(1);
aSet.add(2);
aSet.add(3);

aSet.delete(2);

Удалить последнее вхождение или все вхождения, или первое вхождение?

var array = [2, 5, 9, 5];

// Remove last occurrence (or all occurrences)
for (var i = array.length; i--;) {
  if (array[i] === 5) {
     array.splice(i, 1);
     break; // Remove this line to remove all occurrences
  }
}

или же

var array = [2, 5, 9, 5];

// Remove first occurrence
for (var i = 0; array.length; i++) {
  if (array[i] === 5) {
     array.splice(i, 1);
     break; // Do not remove this line
  }
}

Если вы используете современный браузер, вы можете использовать .filter.

Очень наивная реализация будет выглядеть следующим образом:

Array.prototype.remove = function(data) {
    const dataIdx = this.indexOf(data)
    if(dataIdx >= 0) {
        this.splice(dataIdx ,1);
    }
    return this.length;
}

let a = [1,2,3];
// this will change arr a to [1, 3]
a.remove(2);

Я возвращаю длину массива из функции, чтобы соответствовать другим методам, таким как Array.prototype.push(),

Попробуйте использовать этот код с помощью метода фильтрации, и вы сможете удалить любой конкретный элемент из массива.

пусть arr = [1,2,3,4,5,6,7,8,9];function removeItem(arr, value) {

          return arr.filter(function(ele){ 
        return ele !== value; 
    });
  }
console.log(removeItem(arr, 6))

Использование.indexOf() и.splice() - изменяемый шаблон

Здесь есть два сценария:

  1. мы знаем индекс

const drinks = [ 'Tea', 'Coffee', 'Milk'];
const id = 1;
const removedDrink = drinks.splice(id,  1);
console.log(removedDrink)

  1. мы не знаем индекса, но знаем значение.
    const drinks =  ['Tea','Coffee', 'Milk'];
    const id = drinks.indexOf('Coffee'); // 1
    const removedDrink = drinks.splice(id,  1);
    // ["Coffee"]
    console.log(removedDrink);
    // ["Tea", "Milk"]
    console.log(drinks);

Использование.filter() - Неизменяемый шаблон

Лучший способ подумать об этом - вместо "удаления" элемента вы "создадите" новый массив, который просто не включает этот элемент. Поэтому мы должны его найти и полностью исключить.

const drinks = ['Tea','Coffee', 'Milk'];
const id = 'Coffee';
const idx = drinks.indexOf(id);
const removedDrink = drinks[idx];
const filteredDrinks = drinks.filter((drink, index) => drink == removedDrink);

console.log("Filtered Drinks Array:"+ filteredDrinks);
console.log("Original Drinks Array:"+ drinks);

Другие вопросы по тегам