Reputation: 75
I have a field that inserts object to an array (tasks).
tasks[
description: "test",
id: "unique from date.now()" ]
How do i prevent from adding a same description value into my array.
<div class="container">
<input id="list-input" />
<input id="select-status" value="New" type="hidden"/>
<button id="add">Add To List</button>
</div>
my script
var tasks = [];
$('#add').click(function() {
var desc = $.trim($('#list-input').val());
var date = Date.now(); //for unique value of id
var strDate = date.toString();
var id = strDate.substring(strDate.length-6, strDate.length);
item = {};
if (!desc) {
item.id = "";
alert("Input a description");
return;
}
item.id = id;
item.description = desc;
tasks.push(item);
}
Upvotes: 0
Views: 1256
Reputation: 11318
You CAN have array of objects, so not sure why you changed your initial tasks type? Anyway, you can do something like this:
var tasks = [];
$('#add').click(function() {
var desc = $.trim($('#list-input').val());
var date = Date.now(); //for unique value of id
var strDate = date.toString();
var id = strDate.substring(strDate.length-6, strDate.length);
item = {};
if (!desc) {
item.id = "";
alert("Input a description");
return;
}
item.id = id;
item.description = desc;
for(i=0;i<tasks.length;i++) {
if(tasks[i].description==desc) {
alert('In array!')
return;
}
}
tasks.push(item);
console.log(tasks);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<input id="list-input" />
<input id="select-status" value="New" type="hidden"/>
<button id="add">Add To List</button>
</div>
So, just check if description value already exists in one of objects, inside array.
Upvotes: 2
Reputation: 1511
First off, your tasks
array example is not a valid array i.e.:
[ description: "test", id: "unique from date.now()" ]
Are you meaning to enclose the elements in curly braces?:
[
{ description: "test", id: "unique from date.now()" },
{ description: "test2", id: "unique from date.now()" }
]
If you want to make sure an object with a certain description doesn't already exist in the array, prior to adding the new object, you can loop the array and check for a previous duplicate before adding the new one in a similar way to this.
Upvotes: 0