0

while working around in Js, I need to check if a value in array is present or not & if it exists show error to user, & if not push it in array. here is my code snippet.

<html>
<body>
<label>Enter an New item to add in Stock</label>
<br> </br>
<input type="text" name=" itemName" id="addItemInStock">
<br></br>
<p id="errorMsg"></p>
<button onclick="addToStock()">Add</button>
<p id="showList"></p>
<select id="showInDropDown">
    <option disabled selected style="display: block;">Stock Items</option>
</select>
<script>
    var fruitsfromLS = localStorage.getItem("fruits");
    var fruits = fruitsfromLS ? JSON.parse(fruitsfromLS) : ["Banana", "Orange", "Apple", "Mango"];
    //document.getElementById("showList").innerHTML = fruits;
    var newItem = document.getElementById("addItemInStock");

    function addToStock() {
        if ((newItem.value) === "") {
            document.getElementById("errorMsg").innerHTML = "Blank item cannot be added!!";
            document.getElementById("errorMsg").style.display = "block";
        } else if ((newItem.value) === fruits[i].value)) {
        document.getElementById("errorMsg").innerHTML = "aLREADY IN sTOCK!";
        document.getElementById("errorMsg").style.display = "block";
    } else {
        document.getElementById("errorMsg").style.display = "none";
        fruits.push(newItem.value);
        localStorage.setItem("fruits", JSON.stringify(fruits));
        clearAndShow();
    }
    fillSelect();
   }
Prasad_Joshi
  • 642
  • 3
  • 13
  • 34

3 Answers3

1

Simple use this check:

!!~array.indexOf(element)

It returns true if element is in array, returns false if element is absent.

You can also extend Array type with your own method (i.e. contains), to use it in your code, like this:

Array.prototype.contains = Array.prototype.contains || function(element) {
    return !!~this.indexOf(element);
};

let a = [ -2, -1, 0, 1, 2, 3, 4, 5 ]; // an example of array

console.log( a.contains(-1) );  // true
console.log( a.contains(10) );  // false
0

Please add your local storage code and fillStcok function for complete functionality. The following snippet is for checking duplicate

    var fruits = ["Banana", "Orange", "Apple", "Mango"];
    //document.getElementById("showList").innerHTML = fruits;
    var newItem = document.getElementById("addItemInStock");

    function addToStock() {
        if (newItem.value === "") {
            document.getElementById("errorMsg").innerHTML = "Blank item cannot be added!!";
            document.getElementById("errorMsg").style.display = "block";
        } else if (fruits.indexOf(newItem.value) !== -1) {
          document.getElementById("errorMsg").innerHTML = "ALREADY IN STOCK!";
          document.getElementById("errorMsg").style.display = "block";
        } else {
          document.getElementById("errorMsg").style.display = "none";
          fruits.push(newItem.value);
      }
   }
<label>Enter an New item to add in Stock</label>
<br> </br>
<input type="text" name=" itemName" id="addItemInStock">
<br></br>
<p id="errorMsg"></p>
<button onclick="addToStock()">Add</button>
<p id="showList"></p>
<select id="showInDropDown">
    <option disabled selected style="display: block;">Stock Items</option>
</select>
Gaurav joshi
  • 1,743
  • 1
  • 14
  • 28
  • thanks for answer, but what if some array elements are again removed, I saw errors when array elements are removed if we use `indexOf` in if else condition. How we can achieve it while keeping array intact? – Prasad_Joshi Jan 06 '17 at 11:08
0

You can always use Array.prototype.find() method, with small extend. It's fast and synchronious. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find

var findFunc = function(searchVal, element, index, arr) {
  return searchVal == element
}

var freshOne = fruits.find(findFunc.bind(undefined, newItem.value)) == undefined;

if (freshOne) {
    fruits.push(newItem.value)
} else {
    console.log('Already there');
}
Leonid Lazaryev
  • 326
  • 1
  • 8