verifying If an object is present in the session's array - javascript

here I'm pushing product_detail to an empty array product. At first I'm checking if the array is empty, If so the json data is pushed into the array and updated with session. If not I want to verify if the there exists an object with the id, if so it wont push it. but the condition is not becoming true. Dont know what I'm missing or I'm putting the condition wrongly
var product_details = {
product_id: product._id,
user_id: user_id,
};
if (product.length !== 0) {
if (req.session.product.forEach(function(data) {
(data.product_id == req.params._id)
})) {
return res.send("product already present ");
}
product.push(product_detail);
req.session.product = product;
return res.send(req.session.product);
}
product.push(product_detail);
req.session.product = product;
console.log(req.session);
return res.send(req.session.product);
});

Simply change your nested condition to:
var arrayTrue = true;
req.session.product.forEach(function(data) {
if(data.product_id == req.params._id){
arrayTrue = false;
}
});
if(arrayTrue){
// Doesn't exist...
}
else{
return res.send("Product already present");
}

Related

How to check if array contains item in JavaScript

I have an array of playlists. A playlist has many posts.
I am trying to determine whether the selected playlist already contains the post I choose to add.
Currently, I'm getting "Already added" if any playlist in the playlists array contains that post.
I only want to add posts to playlists that DO NOT already contain that post.
Basically, I want to still be able to add a post to a playlist even if another playlist contains that post.
const confirmAdd = (selectedPlaylist, selectedPost) => {
for(var i = 0; i < playlists.length; i++) {
if (playlists[i].posts.length > 0) {
if (playlists[i].posts.some(post => post.id != selectedPost.id)) {
console.log("Success")
} else {
console.log("Already added")
}
break
} else {
console.log("Success")
break
}
}
}
The playlist parameter to the confirmAdd() function should be playlists since that is what you are using within the function
you can use "indexOf"
let myArray = ["hello", "this", "is", "array"];
if(myArray.indexOf("hello") > -1){
console.log("Hello is available")
}else{
console.log("not available")
}
The indexOf() method returns the position of the first occurrence of a specified value in a string.
This method returns -1 if the value to search for never occurs.
-w3schools
Javascript has a lot of great functions baked in to help with array manipulation.
For this task, you can use .includes() to check an array for duplicate data.
if(playlist.includes(post)){
...do the thing
} else {
...do the other thing
}
So, I guess you have information about the selected playlist and if it's an object let's refer it by an object called selectedPlaylist. In that case your code should be something like below
function confirmAddFn(selectedPlaylist = {}, reqpost = {}) {
//Here Selected Play list is the reference object of the selection
//searching for the post
let filteredPost = selectedPlaylist.posts.items.filter(post => post.id == reqpost.id);
//if there is a post log already exsist
if (filteredPost.length > 0) {
console.log("Already Exsist");
}
else {
//else add to the ref ob
selectedPlaylist.posts.items.push(reqpost);
}
}
Now, in case you don't have the selected object and just have the index of the selected post. the below code should help
function confirmAddFn(playList = [], reqpost = {}, selectedPlayListIndex = -1) {
//Here Selected Play list is the reference object of the selection
let selectedPlaylist = playList[selectedPlayListIndex];
//searching for the post
let filteredPost = selectedPlaylist.posts.items.filter(post => post.id == reqpost.id);
//if there is a post log already exsist
if (filteredPost.length > 0) {
console.log("Already Exsist");
}
else {
//else add to the ref ob
selectedPlaylist.posts.items.push(reqpost);
}
}

Call function if variable does not exist in a filter

I'm doing filtering on a data displayed in a view which is working correctly. I've placed a filter bar at the top of the screen where a user can filter the records. What I want to achieve is when the variable the user enters is not found in the records a function should be called
filterProducts(ev) {
this.productService.list = this.reOrderList;
const val = ev.target.value;
if (val && val.trim() !== '') {
this.productService.list = this.reOrderList.filter((item) => {
return (item.name.toLowerCase().indexOf(val.toLowerCase()) > -1);
});
} else {
// value doesn't exist console.log('call another function')
}
}
Check if any items are left in the array after the filter is complete:
if (this.productService.list.length) {
// The user's query was found in the array
} else {
// The user's query was not found in the array
}

How can I check whether an item exists in localstorage or not using pure javascript

I have a project on pure javascript,and I was working on saving items to localstorage. I only need to save id, name and image of the item i am saving.
My major problem , however is i do not want save duplicate .Therefore before i save i must check whether the exists or not.
I have so far tried several approaches but all seems not to work.Below is my code snippets.
I am able to save item to localstorage with no problems, infact i can save and delete items from localstorage correctly.
const cart_DB = new cartDB();
if( cart_DB.isAddedToCart(cartInfo.id) === false) {
// save item to database
}else {
alert('item already in cart');
return false;
}
class cartDB {
/// save cart into localstorage ////
saveIntoDB(cart) {
const carts = this.getFromDB();
carts.push(cart);
// add the new array into localstorage
localStorage.setItem('carts', JSON.stringify(carts));
}
/// save cart into localstorage ///
/// return carts from storage ///
getFromDB() {
let carts;
// check from local storage
if (localStorage.getItem('carts') === null) {
carts = [];
} else {
carts = JSON.parse(localStorage.getItem('carts'))
}
return carts;
}
/// carts from storage ends ///
/// check if item already exists in database ////////
isAddedToCart(id) {
if (localStorage.getItem(id) === null
||localStorage.getItem(id).length === 0) {
return false;
}else {
return true;
}
}
//// checking items ends here ///////
}
What i want is to check whether the item exists or not before adding another item.
Assuming that you store items in array you can use below function to check if item already exists:
function checkIfItemExists (id) {
const items = localStorage.getItem('carts')
let itemExists = false
if (items) {
const itemsData = JSON.parse(items)
// check if item with given id exists in local storage data
itemExists = itemsData.find(item => item.id === id)
}
return itemExists
}
If your goal is to find out if there's a duplicate, Array.some() would be the best function you are looking for. Implement it to your function like this.
isAddedToCart(id) {
const carts = localStorage.getItem('carts');
return carts.some(cart => cart.id == id);
}
Array.some() Definition and Usage
The some() method checks if any of the elements in an array pass a
test (provided as a function).
The some() method executes the function once for each element present
in the array:
If it finds an array element where the function returns a true value, some() returns true (and does not check the remaining
values)
Otherwise it returns false

How to add value to array after checking another array

I have two arrays as such :
UserGroupUser[{Id:"1",UserId:"2",UserGroupId"1"},
{Id:"2",UserId:"3",UserGroupId"1"},
{Id:"3",UserId:"4",UserGroupId"2"}]
UserGroupId will have values such as 1, 2, 3 etc.
Employee[{EmployeeId:"1", EmpName:"John", Email:"john#example.com"},
{EmployeeId:"2", EmpName:"Mary", Email:"Mary#example.com"},
{EmployeeId:"3", EmpName:"Sarah", Email:"Sarah#example.com"},
{EmployeeId:"4", EmpName:"Jake", Email:"Jake#example.com"} ]
I will store a number in a variable GroupId such as GroupId=1
and what i want to do is check the UserGroupUser table if GroupId 1 matches any rows for key UserGroupId and if there is a match for every UserId the corresponding EmployeeId in Employee table that matches would mean i add a new element called enrolled=true. else if there is not match add a element to Employee enrolled=false.
for eg:
If GroupId is =1 then i want to get the userId of those with the UserGroupId as 1 in the UserGroupUser array and add enrolled:true into the Employee array EmployeeId to those corresponding to the UserId .
This is how i tried to do it..
UserGroupUser.forEach(function (arrayItem) {
if (arrayItem.UserGroupId === GroupId) {
result = Employee.map(function (a, index, array) {
while (arrayItem.UserId === a.EmployeeNo) {
a.enrolled = true;
}
return a;
}
);
}
else {
result = Employee.map(function (a, index, array) {
a.enrolled = false;
return a;
}
);
}
});
what am i doing wrong? how should i do this?
Try this
var userGroup = [{Id:"1",UserId:"2",UserGroupId:"1"},
{Id:"2",UserId:"3",UserGroupId:"1"},
{Id:"3",UserId:"4",UserGroupId:"2"}]
var employees = [{EmployeeId:"1", EmpName:"John", Email:"john#example.com"},
{EmployeeId:"2", EmpName:"Mary", Email:"Mary#example.com"},
{EmployeeId:"3", EmpName:"Sarah", Email:"Sarah#example.com"},
{EmployeeId:"4", EmpName:"Jake", Email:"Jake#example.com"} ]
employees.forEach(function(item){
var found = userGroup.filter(i=>i.UserId==item.Id);
if(found.length>0)
item.enrolled = true
else
item.enrolled = false
})
console.log(employees);
the employees then will contained the enrolled or not try this in your console too
The problem with your code is that when if (arrayItem.UserGroupId === GroupId) { is executed, it changes enrolled to true for the concerned employees but when the else part of this check is executed, it overrides the changes made by the if condition part.
Try this.
UserGroupUser = [{Id:"1",UserId:"2",UserGroupId:"1"},
{Id:"2",UserId:"3",UserGroupId:"1"},
{Id:"3",UserId:"4",UserGroupId:"2"}];
Employee = [{EmployeeId:"1", EmpName:"John", Email:"john#example.com"},
{EmployeeId:"2", EmpName:"Mary", Email:"Mary#example.com"},
{EmployeeId:"3", EmpName:"Sarah", Email:"Sarah#example.com"},
{EmployeeId:"4", EmpName:"Jake", Email:"Jake#example.com"}];
GroupId = "1";
Employee.map(function (emp) {
emp.enrolled = false;
});
UserGroupUser.forEach(function (arrayItem) {
if (arrayItem.UserGroupId === GroupId) {
Employee.map(function (emp) {
if (arrayItem.UserId === emp.EmployeeId) {
emp.enrolled = true;
}
});
}
});
console.log(Employee);

how to use contains functions with array in jquery?

i have an array which contains some values. i want if the textbox's value contains a value from any of the element of that array it will show alert "exists", otherwise "doesn't exists"
I have tried the following code:
$('[id$=txt_Email]').live('blur', function (e) {
var email = $('[id$=txt_Email]').val();
var array = ['gmail.com', 'yahoo.com'];
if (array.indexOf(email) < 0) { // doesn't exist
// do something
alert('doesnot exists');
}
else { // does exist
// do something else
alert('exists');
}
});
But this is comparing the whole value with the array's element. i want to use contains function as we can in C# with string.Please help me.
I want if user type "test#gmail.com" it will show exists in array. if user enter "test#test.com" it will alert doesnot exists.
I think you want
$.each(array, function () {
found = this.indexOf(email);
});
To find the match not exact string you need to do some thing like
Live Demo
arr = ['gmail.com', 'yahoo.com'];
alert(FindMatch(arr, 'gmail.co'));
function FindMatch(array, strToFind)
{
for(i=0; i < array.length; i++)
{
if(array[i].indexOf( strToFind) != -1)
return true;
}
return false;
}
​
$(document).on('blur', '[id$=txt_Email]', function (e) {
var email = this.value, array = ['gmail.com', 'yahoo.com'];
if (email.indexOf('#')!=-1) {
if ($.inArray(email.split('#')[1], array)!=-1) {
alert('exists');
}else{
alert('does not exists');
}
}
});​
FIDDLE
b is the value, a is the array
It returns true or false
function(a,b){return!!~a.indexOf(b)}

Categories

Resources