How do I Dedupe the following array using a hash table - javascript

The array
const users = dedup([
{ id: 1, email: 'foo#example.com' },
{ id: 2, email: 'sho#example.com' },
{ id: 1, email: 'bin#example.com' },
]);
/* would ideally like it to return
Object {
email: "foo#example.com",
email: "bin#example.com",
id:1
}, Object {
email: "sho#example.com",
id:2
} */
The Hash Table
function dedup(arr) {
var hashTable = {};
return arr.filter(function (el) {
var key = JSON.stringify(el);
var match = Boolean(hashTable[key]);
return (match ? false : hashTable[key] = true);
});
}
My returns statement that only filters out exact duplicates and doesn't join similar id's with different email addresses
console.log(users);
/* currently returns
Object {
email: "foo#example.com",
id:1
}, Object {
email: "sho#example.com",
id:2
},
{ id: 1, email: 'bin#example.com' },
]); */

function dedup(arr) {
var hashTable = {};
arr.forEach(function(el) {
if (!hashTable.hasOwnProperty(el.id)) {
hashTable[el.id] = [];
}
hashTable[el.id].push(el.email);
});
return hashTable;
}
Result should be:
{
1: ['bin#example.com', 'foo#example.com' ],
2: ['sho#example.com']
}
Hope this helped.

Related

How to check if a value in an array is present in other object and accordingly return a new object

I have an array
const dataCheck = ["Rohit","Ravi"];
I have another array of object
const userData = [
{ name: "Sagar" },
{ name: "Vishal" },
{ name: "Rohit" },
{ name: "Ravi" },
];
I want to check if any value in dataCheck is present in the userData and then return a new array with the below data
const newData = [
{ name: "Sagar" },
{ name: "Vishal" },
{ name: "Rohit", status: "present" },
{ name: "Ravi", status: "present" },
];
I tried to do something using loops but not getting the expected results
const dataCheck = ["Rohit", "Ravi"];
const userData = [
{ name: "Sagar" },
{ name: "Vishal" },
{ name: "Rohit" },
{ name: "Ravi" }
];
let newDataValue = {};
let newData = [];
userData.forEach((user) => {
const name = user.name;
dataCheck.forEach((userName) => {
if (name === userName) {
newDataValue = {
name: name,
status: "present"
};
} else {
newDataValue = {
name: name
};
}
newData.push(newDataValue);
});
});
console.log(newData);
My trial gives me repeated results multiple results which is just duplicates
You should use map() and a Set.
const dataCheck = ["Rohit","Ravi"];
const userData = [
{ name: "Sagar" },
{ name: "Vishal" },
{ name: "Rohit" },
{ name: "Ravi" },
];
const set = new Set(dataCheck);
const output = userData.map(data => set.has(data.name) ? ({...data, status: "present"}): data)
console.log(output)
.as-console-wrapper { max-height: 100% !important; top: 0; }
A Set allows for lookups in O(1) time and therefore this algorithm works in O(n) time. If you would use the array for lookups (e.g. using indcludes(), find() etc.) the runtime would be O(n²). Although this will certainly not matter at all for such small arrays, it will become more relevant the larger the array gets.
map() is used here because you want a 1:1 mapping of inputs to outputs. The only thing to determine then is, what the output should be. It is either the input, if the value is not in the Set, or it is the input extended by one property status set to "present". You can check for the presence in a Set using the has() method and can use the ternary operator ? to make the decision which case it is.
const dataCheck = ["Rohit", "Ravi"];
const userData = [
{ name: "Sagar" },
{ name: "Vishal" },
{ name: "Rohit" },
{ name: "Ravi" },
];
// map through every object and check if name property
// exists in data check with help of filter.
// if it exists the length of filter should be 1 so
// you should return { name: el.name, status: "present" } else
// return { name: el.name }
let newData = userData.map((el) => {
if (dataCheck.filter((name) => name === el.name).length > 0) {
return { name: el.name, status: "present" };
} else {
return { name: el.name };
}
});
console.log("newdata: ", newData);
A better approach would be to use map over userData array, find for matching element in dataCheck, if found return matching element + a status key or just return the found element as it is.
const dataCheck = ["Rohit","Ravi"];
const userData = [
{ name: "Sagar" },
{ name: "Vishal" },
{ name: "Rohit" },
{ name: "Ravi" },
];
const getUpdatedObject = () => {
return userData.map(userData => {
const userDetail = dataCheck.find(data => userData.name === data);
if(userDetail) return {userDetail, status:"present"}
else return {...userData}
});
}
console.log(getUpdatedObject())
Working fiddle
Loop through userData, check if name is includes in dataCheck. If true add status 'present'.
const dataCheck = ["Rohit","Ravi"];
const userData = [
{ name: "Sagar" },
{ name: "Vishal" },
{ name: "Rohit" },
{ name: "Ravi" },
];
for (let user of userData) {
if(dataCheck.includes(user.name)) {
user.status = 'present'
}
}
console.log(userData)
You are seeing repeated results due to the second loop dataCheck.forEach((userName) => { as every loop of dataCheck will fire the if/else statement and add something to the final array. However many values you add to dataCheck will be however many duplicates you get.
Only need to loop through one array and check if the value is in the other array so no duplicates get added.
const dataCheck = ["Rohit", "Ravi"];
const userData = [{ name: "Sagar" }, { name: "Vishal" }, { name: "Rohit" }, { name: "Ravi" }];
let newDataValue = {};
let newData = [];
// loop thru the users
userData.forEach((user) => {
// set the user
const name = user.name;
// check if in array
if (dataCheck.indexOf(name) >= 0) {
newDataValue = {
name: name,
status: "present",
};
}
// not in array
else {
newDataValue = {
name: name,
};
}
newData.push(newDataValue);
});
console.log(newData);
So you will do like this :
const dataCheck = ["Rohit","Ravi"];
const userData = [
{ name: "Sagar" },
{ name: "Vishal" },
{ name: "Rohit" },
{ name: "Ravi" },
];
const newUserData = userData.map( user => {
dataCheck.forEach( data => {
if( data === user.name )
user.status = "present";
});
return user;
} );
console.log( newUserData );

map an array inside object of an array

So I have an array of objects with many, keys, something like that:
[
{ id: 1,
phoneNumber: 12345,
name: "John",
underLicense: true
},
{ id: 2,
phoneNumber: 12345,
name: "Jane",
underLicense: false
}
]
The way i want it to look like is this:
[
{ listPhone: [
{ number: 12345,
underLicense: true
},
{ number: 12345
underLicense: false
}
]
}
]
so for that, first i do the map(), and then I push it into listPhones
here is my function
saveLicense() {
const listPhone = this.toSend.map(x => {
return {
number: x.phoneNumber,
underLicense: x.underLicense
};
});
const savedPhones = [];
savedPhones.push({listPhone: listPhone});
}
The question is, is there a way to to it in the map() metod, without having to use push in the second step
You could directly map to an expression for a property value.
saveLicense() {
const
savedPhones = [{ listPhone: this.toSend.map(({ phoneNumber: number, underLicense }) =>
({ number, underLicense })
) }];
}
Maybe:
saveLicense () {
const listPhone = this.toSend.map((x) => ({
number: x.phoneNumber,
underLicense: x.underLicense,
}));
const savedPhones = [{ listPhone }];
};
saveLicense() {
const listPhone = this.toSend.map(x => {
return { listPhone: {
number: x.phoneNumber,
underLicense: x.underLicense
}
};
});
return [listPhone]
}

Delete duplicate elements from Array in Javascript [duplicate]

This question already has answers here:
How to get distinct values from an array of objects in JavaScript?
(63 answers)
Get all unique values in a JavaScript array (remove duplicates)
(91 answers)
Closed 6 years ago.
I have array with obejcts email and Id so I want delete duplicate elements who have similar ID's.
Example:
var newarray=[
{
Email:"test1#gmail.com",
ID:"A"
},
{
Email:"test2#gmail.com",
ID:"B"
},
{
Email:"test3#gmail.com",
ID:"A"
},
{
Email:"test4#gmail.com",
ID:"C"
},
{
Email:"test4#gmail.com",
ID:"C"
}
];
Now I need to delete Duplicate elements which have ID's are common.In the sence I am expecting final Array is
var FinalArray=[
{
Email:"test1#gmail.com",
ID:"A"
},
{
Email:"test2#gmail.com",
ID:"B"
},
{
Email:"test5#gmail.com",
ID:"C"
}
];
Use Array.prototype.filter to filter out the elements and to keep a check of duplicates use a temp array
var newarray = [{
Email: "test1#gmail.com",
ID: "A"
}, {
Email: "test2#gmail.com",
ID: "B"
}, {
Email: "test3#gmail.com",
ID: "A"
}, {
Email: "test4#gmail.com",
ID: "C"
}, {
Email: "test5#gmail.com",
ID: "C"
}];
// Array to keep track of duplicates
var dups = [];
var arr = newarray.filter(function(el) {
// If it is not a duplicate, return true
if (dups.indexOf(el.ID) == -1) {
dups.push(el.ID);
return true;
}
return false;
});
console.log(arr);
You could filter it with a hash table.
var newarray = [{ Email: "test1#gmail.com", ID: "A" }, { Email: "test2#gmail.com", ID: "B" }, { Email: "test3#gmail.com", ID: "A" }, { Email: "test4#gmail.com", ID: "C" }, { Email: "test5#gmail.com", ID: "C" }],
filtered = newarray.filter(function (a) {
if (!this[a.ID]) {
this[a.ID] = true;
return true;
}
}, Object.create(null));
console.log(filtered);
.as-console-wrapper { max-height: 100% !important; top: 0; }
ES6 with Set
var newarray = [{ Email: "test1#gmail.com", ID: "A" }, { Email: "test2#gmail.com", ID: "B" }, { Email: "test3#gmail.com", ID: "A" }, { Email: "test4#gmail.com", ID: "C" }, { Email: "test5#gmail.com", ID: "C" }],
filtered = newarray.filter((s => a => !s.has(a.ID) && s.add(a.ID))(new Set));
console.log(filtered);
.as-console-wrapper { max-height: 100% !important; top: 0; }
If you can use Javascript libraries such as underscore or lodash, I recommend having a look at _.uniq function in their libraries. From lodash:
_.uniq(array, [isSorted=false], [callback=_.identity], [thisArg])
Here you have to use like below,
var non_duplidated_data = _.uniq(newarray, 'ID');
Another solution using Array.prototype.reduce and a hash table - see demo below:
var newarray=[ { Email:"test1#gmail.com", ID:"A" }, { Email:"test2#gmail.com", ID:"B" }, { Email:"test3#gmail.com", ID:"A" }, { Email:"test4#gmail.com", ID:"C" }, { Email:"test5#gmail.com", ID:"C" } ];
var result = newarray.reduce(function(hash){
return function(prev,curr){
!hash[curr.ID] && (hash[curr.ID]=prev.push(curr));
return prev;
};
}(Object.create(null)),[]);
console.log(result);
.as-console-wrapper{top:0;max-height:100%!important;}

Flatten a nested json and get object keys

I get json from client side which is nested, I want to faltten it and make the children object keys, preferably using underscore.js.
For example that is my json:
var data = {
or:[
{
dealershipCompany : 11
},
{
authType: 'google'
}],
and: [
{
or: [
{
firstName: {'contains': 'search'}
},
{
lastName: {'contains': 'search'}
},
{
email: {'contains': 'search'}
}]
}]
};
I want to remove both 'or' & 'and'
and when I get the object keys using Object.keys(data) I get
['0','1','2','3','4','5']
but I want it to be like this
['dealershipCompany', 'authType', 'firstName', 'lastName','email']
I tried several times to flatten it by myself but always object keys get numbered
Here the link of jsFiddle
This should work:
var data = {
or:[
{ dealershipCompany : 11 },
{ authType: 'google' }
],
and: [ {
or: [
{ firstName: {'contains': 'search'} },
{ lastName: {'contains': 'search'} },
{ email: {'contains': 'search'} }
]
}]
};
function getOnlyObjects(data) {
var result = [];
if (Array.isArray(data)) {
data.forEach(function(item) {
result = result.concat(
getOnlyObjects(item)
);
});
}
else {
Object.keys(data).forEach(function(key) {
if (Array.isArray(data[key])) {
result = result.concat(
getOnlyObjects(data[key])
);
}
else {
result = result.concat(data);
}
});
}
return result;
}
function getData(data) {
return getOnlyObjects(data).map(function(item) {
return Object.keys(item)[0];
});
}
console.log(getData(data));
Outputs:
["dealershipCompany", "authType", "firstName", "lastName", "email"]
When you use Object.keys over array, you will get indexes, hence you were getting ['0','1','2','3','4','5'].
Edit 1
Have migrated === 'and', === 'or' to an array exceptionList. You can add further keys that you need to filter. This will keep filtering manageable and condition clean.
Code
JSFiddle
var data = {
or: [{
dealershipCompany: 11
}, {
authType: 'google'
}],
and: [{
or: [{
firstName: {
'contains': 'search'
}
}, {
lastName: {
'contains': 'search'
}
}, {
email: {
'contains': 'search'
}
}, ]
}]
};
var result = [];
// You can add further keys that you want to filter
var exceptionList = ["and", "or"];
function getKeys(obj) {
var _keys = Object.keys(obj);
_keys.forEach(function(key) {
// Check if key is either,`and`, `or`, or an index of array.
if (exceptionList.indexOf(key) >=0 || !isNaN(key)) {
getKeys(obj[key]);
} else {
result.push(key);
}
});
}
getKeys(data);
console.log(result)

Check if object value exists within a Javascript array of objects and if not add a new object to array

If I have the following array of objects:
[ { id: 1, username: 'fred' }, { id: 2, username: 'bill' }, { id: 2, username: 'ted' } ]
Is there a way to loop through the array to check whether a particular username value already exists and if it does do nothing, but if it doesn't to add a new object to the array with said username (and new ID)?
Thanks!
I've assumed that ids are meant to be unique here. some is a great function for checking the existence of things in arrays:
const arr = [{ id: 1, username: 'fred' }, { id: 2, username: 'bill' }, { id: 3, username: 'ted' }];
function add(arr, name) {
const { length } = arr;
const id = length + 1;
const found = arr.some(el => el.username === name);
if (!found) arr.push({ id, username: name });
return arr;
}
console.log(add(arr, 'ted'));
This small snippets works for me..
const arrayOfObject = [{ id: 1, name: 'john' }, {id: 2, name: 'max'}];
const checkUsername = obj => obj.name === 'max';
console.log(arrayOfObject.some(checkUsername))
if you have array of elements like ['john','marsh'] then we can do some thing like this
const checkUsername = element => element == 'john';
console.log(arrayOfObject.some(checkUsername))
It's rather trivial to check for existing username:
var arr = [{ id: 1, username: 'fred' },
{ id: 2, username: 'bill'},
{ id: 3, username: 'ted' }];
function userExists(username) {
return arr.some(function(el) {
return el.username === username;
});
}
console.log(userExists('fred')); // true
console.log(userExists('bred')); // false
But it's not so obvious what to do when you have to add a new user to this array. The easiest way out - just pushing a new element with id equal to array.length + 1:
function addUser(username) {
if (userExists(username)) {
return false;
}
arr.push({ id: arr.length + 1, username: username });
return true;
}
addUser('fred'); // false
addUser('bred'); // true, user `bred` added
It will guarantee the IDs uniqueness, but will make this array look a bit strange if some elements will be taken off its end.
There could be MULTIPLE POSSIBLE WAYS to check if an element(in
your case its Object) is present in an array or not.
const arr = [
{ id: 1, username: 'fred' },
{ id: 2, username: 'bill' },
{ id: 3, username: 'ted' },
];
let say you want to find an object with id = 3.
1. find:
It searches for an element in an array and if it finds out then it returns that element else return undefined. It returns the value of the first element in the provided array that satisfies the provided testing function. reference
const ObjIdToFind = 5;
const isObjectPresent = arr.find((o) => o.id === ObjIdToFind);
if (!isObjectPresent) { // As find return object else undefined
arr.push({ id: arr.length + 1, username: 'Lorem ipsum' });
}
2. filter:
It searches for elements in an array and filters out all element that matches the condition. It returns a new array with all elements and if none matches the condition then an empty array. reference
const ObjIdToFind = 5;
const arrayWithFilterObjects= arr.filter((o) => o.id === ObjIdToFind);
if (!arrayWithFilterObjects.length) { // As filter return new array
arr.push({ id: arr.length + 1, username: 'Lorem ipsum' });
}
3. some:
The some() method tests whether at least one element is present in an array that passes the test implemented by the provided function. It returns a Boolean value. reference
const ObjIdToFind = 5;
const isElementPresent = arr.some((o) => o.id === ObjIdToFind);
if (!isElementPresent) { // As some return Boolean value
arr.push({ id: arr.length + 1, username: 'Lorem ipsum' });
}
This is what I did in addition to #sagar-gavhane's answer
const newUser = {_id: 4, name: 'Adam'}
const users = [{_id: 1, name: 'Fred'}, {_id: 2, name: 'Ted'}, {_id: 3, name:'Bill'}]
const userExists = users.some(user => user.name === newUser.name);
if(userExists) {
return new Error({error:'User exists'})
}
users.push(newUser)
I think that, this is the shortest way of addressing this problem. Here I have used ES6 arrow function with .filter to check the existence of newly adding username.
var arr = [{
id: 1,
username: 'fred'
}, {
id: 2,
username: 'bill'
}, {
id: 3,
username: 'ted'
}];
function add(name) {
var id = arr.length + 1;
if (arr.filter(item=> item.username == name).length == 0){
arr.push({ id: id, username: name });
}
}
add('ted');
console.log(arr);
Link to Fiddle
Let's assume we have an array of objects and you want to check if value of name is defined like this,
let persons = [ {"name" : "test1"},{"name": "test2"}];
if(persons.some(person => person.name == 'test1')) {
... here your code in case person.name is defined and available
}
try this
first method using some
let arr = [{ id: 1, username: 'fred' }, { id: 2, username: 'bill' }, { id: 3, username: 'ted' }];
let found = arr.some(ele => ele.username === 'bill');
console.log(found)
second method using includes, map
let arr = [{ id: 1, username: 'fred' }, { id: 2, username: 'bill' }, { id: 3, username: 'ted' }];
let mapped = arr.map(ele => ele.username);
let found = mapped.includes('bill');
console.log(found)
You could prototype your array to make it more modular, try something like this
Array.prototype.hasElement = function(element) {
var i;
for (i = 0; i < this.length; i++) {
if (this[i] === element) {
return i; //Returns element position, so it exists
}
}
return -1; //The element isn't in your array
};
And you can use it as:
yourArray.hasElement(yourArrayElement)
Accepted answer can also be written in following way using arrow function on .some
function checkAndAdd(name) {
var id = arr.length + 1;
var found = arr.some((el) => {
return el.username === name;
});
if (!found) { arr.push({ id: id, username: name }); }
}
Here is an ES6 method chain using .map() and .includes():
const arr = [ { id: 1, username: 'fred' }, { id: 2, username: 'bill' }, { id: 2, username: 'ted' } ]
const checkForUser = (newUsername) => {
arr.map(user => {
return user.username
}).includes(newUsername)
}
if (!checkForUser('fred')){
// add fred
}
Map over existing users to create array of username strings.
Check if that array of usernames includes the new username
If it's not present, add the new user
I like Andy's answer, but the id isn't going to necessarily be unique, so here's what I came up with to create a unique ID also. Can be checked at jsfiddle too. Please note that arr.length + 1 may very well not guarantee a unique ID if anything had been removed previously.
var array = [ { id: 1, username: 'fred' }, { id: 2, username: 'bill' }, { id: 3, username: 'ted' } ];
var usedname = 'bill';
var newname = 'sam';
// don't add used name
console.log('before usedname: ' + JSON.stringify(array));
tryAdd(usedname, array);
console.log('before newname: ' + JSON.stringify(array));
tryAdd(newname, array);
console.log('after newname: ' + JSON.stringify(array));
function tryAdd(name, array) {
var found = false;
var i = 0;
var maxId = 1;
for (i in array) {
// Check max id
if (maxId <= array[i].id)
maxId = array[i].id + 1;
// Don't need to add if we find it
if (array[i].username === name)
found = true;
}
if (!found)
array[++i] = { id: maxId, username: name };
}
i did try the above steps for some reason it seams not to be working for me but this was my final solution to my own problem just maybe helpful to any one reading this :
let pst = post.likes.some( (like) => { //console.log(like.user, req.user.id);
if(like.user.toString() === req.user.id.toString()){
return true
} } )
here post.likes is an array of users who liked a post.
Greatly simplifying my previous solutions here and providing better performance by not iterating over the entire array unnecessarily before checking for the existence of the specified ID.
This should be the simplest solution (I think):
const users = [{ id: 1, username: 'fred' }, { id: 2, username: 'bill' }, { id: 3, username: 'ted' }];
const addUser = (username) => {
const user = users.find((user) => user.username === username);
if (user) return { ...user, new: false };
const newUser = {
id: users.length + 1,
username,
};
users.push(newUser);
return { ...newUser, new: true };
};
Here is how that might look as a live example:
const users = [{ id: 1, username: 'fred' }, { id: 2, username: 'bill' }, { id: 3, username: 'ted' }];
const addUser = (username) => {
const user = users.find((user) => user.username === username);
if (user) return { ...user, new: false };
const newUser = {
id: users.length + 1,
username,
};
users.push(newUser);
return { ...newUser, new: true };
};
// a little extra scripting here to support the input and button in the example
const form = document.querySelector('form');
const input = document.querySelector('input');
const span = document.querySelector('span');
const pre = document.querySelector('pre');
const syncDataWithPre = () => {
pre.innerHTML = JSON.stringify(users, null, 2);
};
form.onsubmit = (e) => {
e.preventDefault();
span.textContent = '';
if (input.value) {
const user = addUser(input.value);
const { new: isNew, ...userDetails } = user;
span.classList[isNew ? 'add' : 'remove']('new');
span.textContent = `User ${isNew ? 'added' : 'already exists'}`;
}
input.value = '';
syncDataWithPre();
};
syncDataWithPre();
body {
font-family: arial, sans-serif;
}
span {
display: block;
padding-top: 8px;
font-weight: 700;
color: #777;
}
span:empty {
display: none;
}
.new {
color: #0a0;
}
.existing: {
color: #777;
}
<form>
<input placeholder="New username" />
<button>Add user</button>
</form>
<span></span>
<pre></pre>
Native functions of array are sometimes 3X - 5X times slower than normal loops. Plus native functions wont work in all the browsers so there is a compatibility issues.
My Code:
<script>
var obj = [];
function checkName(name) {
// declarations
var flag = 0;
var len = obj.length;
var i = 0;
var id = 1;
// looping array
for (i; i < len; i++) {
// if name matches
if (name == obj[i]['username']) {
flag = 1;
break;
} else {
// increment the id by 1
id = id + 1;
}
}
// if flag = 1 then name exits else push in array
if (flag == 0) {
// new entry push in array
obj.push({'id':id, 'username': name});
}
}
// function end
checkName('abc');
</script>
This way you can achieve result faster.
Note: I have not checked if parameter passed is empty or not, if you want you can put a check on it or write a regular expression for particular validation.
xorWith in Lodash can be used to achieve this
let objects = [ { id: 1, username: 'fred' }, { id: 2, username: 'bill' }, { id: 2, username: 'ted' } ]
let existingObject = { id: 1, username: 'fred' };
let newObject = { id: 1729, username: 'Ramanujan' }
_.xorWith(objects, [existingObject], _.isEqual)
// returns [ { id: 2, username: 'bill' }, { id: 2, username: 'ted' } ]
_.xorWith(objects, [newObject], _.isEqual)
// returns [ { id: 1, username: 'fred' }, { id: 2, username: 'bill' }, { id: 2, username: 'ted' } ,{ id: 1729, username: 'Ramanujan' } ]
Check it here :
https://stackoverflow.com/a/53644664/1084987
You can create something like if condition afterwards, like
if(!contains(array, obj)) add();
You can try this also
const addUser = (name) => {
if (arr.filter(a => a.name == name).length <= 0)
arr.push({
id: arr.length + 1,
name: name
})
}
addUser('Fred')
function number_present_or_not() {
var arr = [2, 5, 9, 67, 78, 8, 454, 4, 6, 79, 64, 688];
var found = 6;
var found_two;
for (i = 0; i < arr.length; i++) {
if (found == arr[i]) {
found_two = arr[i];
break;
}
}
if (found_two == found) {
console.log('number present in the array');
} else {
console.log('number not present in the array');
}
}
I was given a condition to check the data in the table of the mysql database the object array of my table consist of the id, latitude and longitude as column names, I have to check whether the location is in the database else insert this into the table so:
I created a function of handle submit called by a button,
handle Submit = (event) => {
const latitude = document.getElementById("latitude").innerHTML;
const longitude = document.getElementById("longitude").innerHTML;
const found = this.state.data.some((el) => el.latitude === latitude);
if (!found) {
Axios.post("http://localhost:3001/api/insert", {
latitude: latitude,
longitude: longitude,
}).then(() => {
alert("successful insert");
});
console.log(latitude, longitude);
}
};
Here you can see the conditional statement for inserting if not exist in the database.
Please have a look on given example
$(document).ready(function(){
const arr = document.querySelector(".list");
var abcde = [{ id: 1, username: 'fred' }, { id: 2, username: 'bill' }, { id: 2, username: 'ted' }];
$("#btnCheckUser").click(function() {
var tbUsername = $("#tbUsername").val();
if (abcde.some(obj => obj.username === tbUsername)) {
alert('existing user ' + tbUsername);
return;
}
else {
abcde.push({ id: abcde.length + 1, username: tbUsername });
alert('added new user ' + tbUsername);
arr.appendChild(createArray(tbUsername));
return;
}
});
function createArray(name) {
let li = document.createElement("li");
li.textContent = name;
return li;
}
abcde.forEach((x) => arr.appendChild(createArray(x.username)));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<p>Add text and click on Check.</p>
<input type="text" id="tbUsername" />
<button type="button" id="btnCheckUser">Check</button>
<div class="list">
<ul></ul>
</div>
const __checkIfElementExists__ = __itemFromArray__ => __itemFromArray__.*sameKey* === __outsideObject__.*samekey*;
if (cartArray.some(checkIfElementExists)) {
console.log('already exists');
} else {
alert('does not exists here')

Categories