How to check if array contains item in JavaScript - 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);
}
}

Related

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

Array returning empty in Javascript

This is all still pretty new to me but I am running into an interesting behavior issue when generating an array of numbers in a NodeJS application that handles .nessus result files. First, some details on what I am trying to accomplish. My application generates an array [1234,1223,1222] of entries from an uploaded "results" file that is then used to query a mongodb instance to determine if those entries are currently in the DB. If those entries are not currently in the mongodb instance, it redirects to a page where a user can edit them before being added. If there are no new entries, it goes to a page to generate a report on the entries.
When a file is uploaded, it stores the new entries. In .nessus files, sometimes there is more than one host with entries. That changes the json structure and the function needs to iterate a little differently. The following function is how those entries are stored. This is important as this is where the weird behavior originates (I think)
function parsePluginNumbers(json){
var pluginNumbers = []
//Let's check the number of hosts
var hostLength = json['NessusClientData_v2']['Report'].ReportHost.length
if (hostLength != undefined) {
for (var i = 0; i < hostLength; i++) { //Since there is more than 1, need to iterate over each host to find the findings.
var item_length = json['NessusClientData_v2']['Report'].ReportHost[i].ReportItem.length
for (var t = 0; t < item_length; t++) { //Iterate through each finding on each host
if (json['NessusClientData_v2']['Report'].ReportHost[i].ReportItem[t].risk_factor != 'None') {
var newEntry = json['NessusClientData_v2']['Report'].ReportHost[i].ReportItem[t].pluginID
if (pluginNumbers.indexOf(newEntry) == -1) {
pluginNumbers.push(newEntry)
}
else {
continue
}
} else {
continue
}
}
}
} else {
var item_length = json['NessusClientData_v2']['Report']['ReportHost'].ReportItem.length
for (var t = 0; t < item_length; t++) { //Iterate over findings
if (json['NessusClientData_v2']['Report']['ReportHost'].ReportItem[t].risk_factor != 'None') {
var newEntry = json['NessusClientData_v2']['Report']['ReportHost'].ReportItem[t].pluginID
if (pluginNumbers.indexOf(newEntry) == -1) {
pluginNumbers.push(newEntry)
}
else {
continue
}
} else {
continue
}
}
}
return pluginNumbers
}
Once those plugins are stored. Another function is called to look if those results are in the mongodbinstance. In this function, those plugins are in an array "pluginsTotal".
function queryForNewResultsInANessusFile(pluginsTotal, collectionname, filename){ //function to call mongodb query and send results to parseNewFindings and parseOldFindings.
var db = req.db;
var collection = db.get(collectionname);
collection.find({ 'PluginNumber' : { $in: pluginsTotal }}, 'FindingTitle FindingDescription Remediation Mitigation SeeAlso PluginFamily PluginNumber CVE Risk -_id', function(error, result){
var newPluginArray = parseOutFindingNumbersInMongoDB(result, pluginsTotal);
//IF statements go here with specific redirects as needed to check if there are new values not in the repo
}
During this collection.find call, there is a function parseOutFindingNumbersInMongoDB that is called to determine if there are plugins in the .nessus results file that are not in the repo. It compares the results from collection.find and pluginsTotal (generated from the first function) and returns an array of the new plugins that are not in the repo. The function details are below:
function parseOutFindingNumbersInMongoDB(repoResults, reportPlugins) {
for (var i = 0; i < repoResults.length; i++){
var index = reportPlugins.indexOf(repoResults[i].PluginNumber);
if (index != -1) {
reportPlugins.splice(index, 1);
}
else {
continue
}
}
return reportPlugins
}
Now to my question --- When I upload a .nessus file with more than one host, parseOutFindingNumberInMongoDB always returns empty even though there are new entries. What gives? Is it the way I parse out the numbers to begin with in the parsePluginNumbers function or is because it is called in the collection.find synchronous function (This seems unlikely as if there is one host, it returns the new plugin values as I want)? Any thoughts/ideas/review would be much appreciated as I cannot figure out what is wrong. I have checked the data types within the array before being passed into the functions and they all match up.
It's always returning an empty array because every element in the array matches the condition to be spliced.
You first retrieve elements that have a PluginNumber in pluginTotal array with this filter { $in: pluginsTotal }
collection.find({ 'PluginNumber' : { $in: pluginsTotal }}, 'FindingTitle FindingDescription Remediation Mitigation SeeAlso PluginFamily PluginNumber CVE Risk -_id', function(error, result){
var newPluginArray = parseOutFindingNumbersInMongoDB(result, pluginsTotal);
}
Then you remove all elements that have a PluginNumber in pluginTotal
var index = reportPlugins.indexOf(repoResults[i].PluginNumber);
if (index != -1) {
reportPlugins.splice(index, 1);
}
So the result is always an empty array.

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

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");
}

Meteor detecting existence of field in collection

Pseudo code below. My result collection of products has an optional subarray of images. What I'm trying to do is check if images exists for a product before trying to access an image.href to use as an image source. In the case where images does NOT exist it breaks every time. Alternately I've tried typeof 'undefined' and that didn't work either.
if (this.products) {
//return "<i class='fa fa-gift'></i>"
console.log("has products");
if (this.products[0].images) { <--- breaks
console.log("item 0 has images");
}
if (this.products.images) { <--- breaks
console.log("has images");
}
} else {
console.log("don't have products");
}
EDIT / UPDATE
Ultimately I think Patrick Lewis supplied the best answer for this - using a hybrid ternary operator. Goes like:
myVar = object && object.name || "foo"
above would assign myVar the name value if the object exists and it has a name, or... it will assign static "foo".
Probably this.products is an empty array. Try:
if (this.products && this.products.length) {
var images = this.products[0].images;
if (images && images.length) {
console.log("item 0 has images");
} else {
console.log("item 0 does not have images");
}
} else {
console.log("don't have products");
}
this.products is your collection or the result of a query like MyColl.find() ?
if this is the result of a query you could do this :
if (typeof this.products == "object") {
if (typeof this.products.images == "object") { // if images is a property of products and images is an array
// od what you want here
}
}

Categories

Resources