简体   繁体   中英

javascript remove item from array, if an item already existing in array

following adds items to array:

var arrayOptions = [];

function AddToFilterOptionList(mode) {
    arrayOptions.push(mode);
    }

remove item from array:

function RemoveFromFilterOptionList(mode) {
    var index = arrayOptions.indexOf(mode);
    if (index !== -1) {
        arrayOptions.splice(index, 1);
    }}

for example if i call

AddToFilterOptionList('APPLE') - APPLE should be added to array.

If i again call

AddToFilterOptionList('APPLE+FRUIT') - it should remove the the item ' APPLE ' from array arrayOptions and should add APPLE+FRUIT

Any time only one word that starts with APPLE can be in array. How to find the word like 'APPLE' in javascript.

I tried with Match() which returns the matching word. IndexOf() returns 1 only if whole word is match but not start of word.

Cycle through the Array and then use the startsWith method.

void AddToFilterOptionList(String mode) {
    for (i=0; i<arrayOptions.length; i++) {
      if (mode.startsWith(arrayOptions[i] == 1)) {
        array[i] = mode;
        return;  // found, so return
      }
    }
    arrayOptions.push(mode); // should only get here if string did not exist.
 }

This will work assuming the 'this+that' pattern is consistent, and that we only care about the starting item.

http://jsbin.com/gefasuqinu/1/edit?js,console

var arr = [];

function remove(item) {
  var f = item.split('+')[0];

  for (var i = 0, e = arr.length; i < e; i++) {
    if (arr[i].split('+')[0] === f) {
      arr.splice(i, 1);
      break;
    }
  }
}

function add(item) {
  remove(item);
  arr.push(item);
}

UPDATE:

function add (array, fruits) {
  var firstFruit = fruits.split('+')[0]
  var secondFruit = fruits.split('+')[1]
  var found = false
  var output = []

  output = array.map(function (item) {
    if (item.indexOf(firstFruit) > -1) {
      found = true
      return fruits
    }
    else return item
  })

  if (! found) {
    array.push(fruits)
  }

  return output
}

var fruits = []
add(fruits, 'APPLE')
fruits = add(fruits, 'APPLE+GRAPE')
console.log(fruits[0]) // 'APPLE+GRAPE'
fruits = add(fruits, 'APPLE')
console.log(fruits[0]) // 'APPLE'

You need to split by + characted and then loop over produced array to add/remove all items:

 var arrayOptions = []; function AddToFilterOptionList(mode) { mode.split(/\\+/g).forEach(function(el) { var index = arrayOptions.indexOf(el); if (index !== -1) { arrayOptions.splice(index, 1); } else { arrayOptions.push(el); } }); } function RemoveFromFilterOptionList(mode) { var index = arrayOptions.indexOf(mode); if (index !== -1) { arrayOptions.splice(index, 1); } } AddToFilterOptionList('APPLE'); document.write('<p>' + arrayOptions); // expect: APPLE AddToFilterOptionList('APPLE+FRUIT'); document.write('<p>' + arrayOptions); // expect: FRUIT AddToFilterOptionList('APPLE+FRUIT+CARROT'); document.write('<p>' + arrayOptions); // expect: APPLE,CARROT 

Try this, the code is not optimised though :P

<html>
    <head>
        <script src = "jquery-1.10.2.min.js"></script>
        <script type = "text/javascript">
            var itemList = [];  
            function addItem()
            {
                var item = $('#item').val();
                if(item != '' || item != 'undefined')
                {
                    if(itemList.length == 0)
                        itemList.push(item);
                    else
                    {
                        for(i=0;i<itemList.length;i++)
                        {
                            var splittedInputItems = [];
                            splittedInputItems = item.split("+");
                            var splittedListItems = [];
                            splittedListItems = itemList[i].split("+");
                            if(splittedListItems[0] == splittedInputItems[0])
                            {
                                itemList.splice(i,1);
                                itemList.push(item);
                                return;
                            }
                        }
                        itemList.push(item);
                    }
                }
            }
        </script>
    </head>
    <body>
        <input id="item" type = "text"/>
        <input type = "button" value="Add" onclick="addItem()">
    </body>
</html>
let items = [1, 2, 3, 2, 4, 5, 2, 7];
let item = 2;
for (let i = 0; i < items.length; i++) {
    if (items[i] === item) {
        items.splice(i, 1);
        i = i - 1;
    }
}

If you want to remove the element '2' from items array, it is a way.

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