0

I have a array named sbjCodeArr

let sbjCodeArr = new Array();

And every time I click the button, data will push into sbjCodeArr

Ex)

  1. First time I click the button ['a']
  2. Second time I click the button ['a', 'b']
  3. Third time I click the button ['a', 'b', 'c']

But if, when I tried to push already exist element like 'a', then I want to prevent push 'a' again and alert message.

I tried like this code but it's not working. td.eq(0).text() is a variable and every time I click the button it will hange and this value should be checked for a duplicate in the array (sbjCodeArr).

let results=[];
for (var i = 0; i < sbjCodeArr.length; i++) {
    if (sbjCodeArr[i + 1] == sbjCodeArr[i]) {
        results.push(td.eq(0).text());
    }
    alert('repeated');
}
console.log(results);

How can I do that?

5

2 Answers 2

2

if you want to prevent content being added, you can check that it already exists in the array you can do an if statement like:

if (!sbjCodeArr.includes(value)) {
  sbjCodeArr.push(value);
}
Sign up to request clarification or add additional context in comments.

Comments

1

I used indexOf, I find it easier to work with it, it looks for the element inside the array, if the element exists it returns the index number of it (starting with 0), if it does not exist it returns -1. As I want to know if the element exists I ask if the search result is -1, if it writes in the array, otherwise it just does not write.

See the example below:

//test presets
var sbjCodeArr = new Array();
sbjCodeArr = ["a", "b", "c"];

//variable with the new value to be added in the array
var newPush = prompt("Please put a new value", "d");

//add if it is not in the array, and sends a warning if
if(sbjCodeArr.indexOf(newPush)==-1){
	//If the array does not have this element
	sbjCodeArr.push(newPush);
}else{
	//If the array already has this element
	alert("Array already has "+newPush)
}

//throws the value of the new array in the console for verification
console.log(sbjCodeArr);

I hope this helps!


Edit: If you use a current browser, you can use the includes method, since it is from ES 7, very current, to work in older places it is better to use indexOf.

1 Comment

Thanks! I solved with this solution!. Actually, I normally use chrome browser and uses nodejs so indexOf method it fine with me. I read the includes method, but still not working in IE :( so sad. I hope most of the browsers should support earlier syntax.

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.