Programing

Javascript 배열 검색 및 문자열 제거?

lottogame 2020. 8. 15. 09:43
반응형

Javascript 배열 검색 및 문자열 제거?


나는 가지고있다:

var array = new Array();
array.push("A");
array.push("B");
array.push("C");

나는 다음과 같은 것을 할 수 있기를 원합니다.

array.remove("B");

그러나 제거 기능은 없습니다. 어떻게해야합니까?


실제로이 스레드를 최신 단선 솔루션으로 업데이트하고 있습니다.

let arr = ['A', 'B', 'C'];
arr = arr.filter(e => e !== 'B'); // will return ['A', 'C']

아이디어는 기본적으로 제거하려는 요소와 다른 모든 요소를 ​​선택하여 배열을 필터링하는 것입니다.

참고 : 모든 항목을 제거합니다.


목록을 역순으로 반복하고 .splice방법을 사용하십시오 .

var array = ['A', 'B', 'C']; // Test
var search_term = 'B';

for (var i=array.length-1; i>=0; i--) {
    if (array[i] === search_term) {
        array.splice(i, 1);
        // break;       //<-- Uncomment  if only the first term has to be removed
    }
}

검색 용어의 모든 발생을 제거해야하는 경우 역순이 중요 합니다. 그렇지 않으면 카운터가 증가하고 요소를 건너 뜁니다.

첫 번째 발생 만 제거해야하는 경우 다음도 작동합니다.

var index = array.indexOf(search_term);    // <-- Not supported in <IE9
if (index !== -1) {
    array.splice(index, 1);
}

데모

찾고있는 위치를 찾은 .indexOf()다음 제거해야합니다..splice()

function remove(arr, what) {
    var found = arr.indexOf(what);

    while (found !== -1) {
        arr.splice(found, 1);
        found = arr.indexOf(what);
    }
}

var array = new Array();
array.push("A");
array.push("B");
array.push("C");
remove(array, 'B');
alert(array)​​​​;

This will take care of all occurrences.


List of One Liners

Let's solve this problem for this array:

var array = ['A', 'B', 'C'];

1. Remove only the first: Use If you are sure that the item exist, Not supported in <IE9

array.splice(array.indexOf('B'), 1);

2. Remove only the last: Use If you are sure that the item exist, Not supported in <IE9

array.splice(array.lastIndexOf('B'), 1);

3. Remove all occurrences: Not supported in <IE9

array = array.filter(v => v !== 'B'); 

Simply

array.splice(array.indexOf(item), 1);

Simple solution (ES6)

If you don't have duplicate element

Array.prototype.remove = function(elem) {
  var indexElement = this.findIndex(el => el === elem);
  if (indexElement != -1)
    this.splice(indexElement, 1);
  return this;
};   

Online demo (fiddle)


You have to write you own remove. You can loop over the array, grab the index of the item you want to remove, and use splice to remove it.

Alternatively, you can create a new array, loop over the current array, and if the current object doesn't match what you want to remove, put it in a new array.


use:

array.splice(2, 1);

This removes one item from the array, starting at index 2 (3rd item)


use array.splice

/*array.splice(index , howMany[, element1[, ...[, elementN]]])

array.splice(index) // SpiderMonkey/Firefox extension*/

array.splice(1,1)

Source: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice


const changedArray = array.filter( function(value) {
  return value !== 'B'
});

or you can use :

const changedArray = array.filter( (value) => value === 'B');

The changedArray will contain the without value 'B'

참고URL : https://stackoverflow.com/questions/9792927/javascript-array-search-and-remove-string

반응형