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();
   }
5
  • 1
    does indexOf not work for you? Commented Jan 6, 2017 at 10:56
  • no , but if I remove some array elements it will again cause error, so I am avoiding to use with indexOf Commented Jan 6, 2017 at 10:57
  • see this:stackoverflow.com/questions/237104/… Commented Jan 6, 2017 at 10:59
  • what is i in your code.fruits[i] Commented Jan 6, 2017 at 10:59
  • you have also a security problem with localStorage and a syntax error here ` } else if ((newItem.value) === fruits[i].value)) {` to much parenthesis. Commented Jan 6, 2017 at 11:03

3 Answers 3

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
Sign up to request clarification or add additional context in comments.

Comments

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>

1 Comment

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?
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');
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.