How to check if item already exists in object array? - javascript

I would like to check if an item.name already exists in the object array so it will not push that existing object to the array.
This is the piece of code:
loadedVariations.forEach(function(item){
console.log('item', item.name.indexOf(name));
if(name === tests[test].id && item.name.indexOf(name) < 0){
console.log(item.name)
loadedVariations.push({name: name, variation: variation});
tests[test].callback(name, variation);
console.log('tests', tests[test], variation, loadedVariations);
if(variation === '1'){
value = "control"
} else {
value = "variationb"
}
localStorage.setItem('gtmTest', JSON.stringify(loadedVariations));
}
})
This is the output in my localstorage:
gtmTest:
[{"name":"globalPassFrame_review","variation":"1"},
{"name":"globalPassFrame_review","variation":"1"},
{"name":"socialshare_bar","variation":"2"},
{"name":"socialshare_bar","variation":"2"}]
This is an AB Test in google tag manager with an helping script which runs on multiple test scripts so it runs multiple times that's why I need to check if item already exists in the object array so it doesn't push the same object twice.

Here is how do you can iterate over your json object by using every and match name . If you want to have array of unique Names you can iterate using forEach and check if it is not present in array .
var object = [{"name":"globalPassFrame_review","variation":"1"},{"name":"globalPassFrame_review","variation":"1"},{"name":"socialshare_bar","variation":"2"},{"name":"socialshare_bar","variation":"2"}];
var tobeFound='globalPassFrame_review';
object.every(function (elem, i) {
if(elem.name == tobeFound ){
console.log('element found at index '+i);
return false ;
}
});
// In case you want to store uniue Names
var uniqueNames=[];
object.forEach(function (elem, i) {
if(!uniqueNames.includes(elem.name)){
uniqueNames.push(elem.name);
}
});
console.log(`unique Names are ${uniqueNames}`);
// Using ES6 style of code.
const uniqueNamesArr = [...new Set( object.map(obj => obj.name)) ];
console.log(uniqueNamesArr);

Related

change of source foreach to other

Manager example
// Create a new array
var gryfindor = [];
// Loop through each wizard
wizards.forEach(function (wizard) {
// If the wizard is in Gryfindor, push to the new array
if (wizard.house === 'Gryfindor') {
gryfindor.push(wizard);
}
});
My manager asked me to write this thing into in this format below:
// Create a new array from the wizard array
var gryfindor = wizards.filter(function (wizard) {
// Only include wizards from the Gryfindor house
return wizard.house === 'Gryfindor';
});
I need to change the foeeach in JavaScript but I don't know how to do anyone can write it or encode
var isExist = false;
var cashoutIndex = 0;
CashOutData.forEach((item, index) => {
if (item.id === userBets[0][i].id) {
isExist = true;
cashoutIndex = index;
}
});
Change of for each loop and faster the performance
answer as per manager required format
Your code does not need to enumerate every item in the list in most cases.
The following code finds the index of the first matching element, and then constructs the response accordingly.
Boolean(~index) uses the bitwise NOT operator to convert the not found signal (-1) from findIndex to a falsy number (0).
const go = (data, userBets) => {
const index = data.findIndex(({id}, i) =>
id === userBets[0]?.[i]?.id)
return [ Boolean(~index), index === -1 ? 0 : index ]
}
const [ isExist, cashoutIndex ] = go(CashOutData, userBets)

Searching For Existing Values in Array

I have been trying to search for an existing value in an array like below
var values = []
values.push(localStorage.getItem('items'));
console.log(values);
if (values.includes(2)) {
alert('Already Exists.');
}
When i console the array values i have output as ["1,2,3,4,5,6"] so the code treats the array as having just one index which is index[0] which makes the search quite challenging for me.
My challenge is how to find the value 2 in the array values ?
localStorage can only hold strings. As such you need to convert the value you retrieve in to an array, which can be done using split().
Also note that the resulting array will contain string values, so you need to use includes('2'). Try this:
var values = "1,2,3".split(','); // just for this demo
//var values = localStorage.getItem('items').split(',');
console.log(values);
if (values.includes("2")) {
console.log('Already Exists.');
}
Hope this help you.
var names_arr = '["1,2,3,4,5,6"]';
names_arr = names_arr.replace("'",'');
function checkValue(value,arr){
var status = 'Not exist';
for(var i=0; i<arr.length; i++){
var name = arr[i];
if(name == value){
status = 'Exist';
break;
}
}
return status;
}
console.log('status : ' + checkValue('3', names_arr) );
console.log('status : ' + checkValue('10', names_arr) );
First of all, this isn't jQuery, it's vanilla JS.
Second, after doing localStorage.setItem("items", [1,2,3,4,5,6]);, items in local storage will equal to "1,2,3,4,5,6", which is no longer the appropriate format.
Rather, save your array with localStorage.setItem("items", JSON.stringify([1,2,3,4,5,6]));. When you want to retrieve those items, write let vals = JSON.parse(localStorage.getItem("items"));, and search in vals with
vals.includes(2) for a true/false answer,
vals.find(val => val === 2) for 2 or undefined,
val.indexOf(2) to get the index of the
first element equal to 2.
Hope this helps.
firstly get the values from local storage store it in a variable, split it using the split
function, then check if the number is inside the array, alert the message if it returns true
var values =localStorage.getItem('items')
var spliter = values.split(',')
console.log(spliter);
if (spliter.includes('2') == true) {
alert('Already Exists.');
}

How to Remove or avoid duplicate values in LocalStorage

When user click on button it will store some value in LocalStorage and if user click same button again it will store same value again in LocalStorage, How can i remove or avoid duplicates same values in LocalStorage ?!
Can anyone please help me :)
HTML:
<a onclick="AddToCart('ae90ac1a-64c4-49a7-b588-ae6b69a37d47');">Add to Cart</a>
<a onclick="AddToCart('3e58aa74-4585-4bee-b2e0-ed39a1d95442');">Add to Cart</a>
JavaScript:
function AddToCart(varer) {
var itemsLocalStorage = JSON.parse(localStorage.getItem("itemsline") || "[]");
itemsLocalStorage.push(varer);
localStorage.setItem("itemsline", JSON.stringify(itemsLocalStorage));
}
LocalStorage (Before user click) :
[]
LocalStorage (When user click ):
["ae90ac1a-64c4-49a7-b588-ae6b69a37d47"]
LocalStorage (When user click again):
["ae90ac1a-64c4-49a7-b588-ae6b69a37d47","ae90ac1a-64c4-49a7-b588-ae6b69a37d47"]
I tried with filter but for some reason it's not going to work:
itemsLocalStorage = itemsLocalStorage.filter(e => e === varer);
Grab the array from localStorage, push the value to the array if it's not found in that array already, and then update localStorage if we pushed.
var array = JSON.parse(window.localStorage.getItem("itemsline")) || [];//the "|| []" replaces possible null from localStorage with empty array
var value = "some value";
if(array.indexOf(value) == -1){
array.push(value);
window.localStorage.setItem("itemsline", JSON.stringify(array));
}
Here's a version of this same code that is more explanatory of how it works:
//All values stored in localStorage are strings.
//Grab our itemsline string from localStorage.
var stringFromLocalStorage = window.localStorage.getItem("itemsline");
//Then parse that string into an actual value.
var parsedValueFromString = JSON.parse(stringFromLocalStorage);
//If that value is null (meaning that we've never saved anything to that spot in localStorage before), use an empty array as our array. Otherwise, just stick with the value we've just parsed out.
var array = parsedValueFromString || [];
//Here's the value we want to add
var value = "some value";
//If our parsed/empty array doesn't already have this value in it...
if(array.indexOf(value) == -1){
//add the value to the array
array.push(value);
//turn the array WITH THE NEW VALUE IN IT into a string to prepare it to be stored in localStorage
var stringRepresentingArray = JSON.stringify(array);
//and store it in localStorage as "itemsline"
window.localStorage.setItem("itemsline", stringRepresentingArray);
}
Take temp array and then check for duplicate values.
var arr = ["ae90ac1a-64c4-49a7-b588-ae6b69a37d47","ae90ac1a-64c4-49a7-b588-ae6b69a37d47"]
function squash(arr){
var tmp = [];
for(var i = 0; i < arr.length; i++){
if(tmp.indexOf(arr[i]) == -1){
tmp.push(arr[i]);
}
}
return tmp;
}
console.log(squash(arr));
You could use filter
array.filter((item, index) => array.indexOf(item) === index)
const array = ["ae90ac1a-64c4-49a7-b588-ae6b69a37d47","ae90ac1a-64c4-49a7-b588-ae6b69a37d47"];
const filteredArray = array.filter((item, index) => array.indexOf(item) === index);
console.log(filteredArray)
You can use Set object of js it always add value only when it is unique
var array = JSON.parse(localStorage.getItem("items")) || [];
let set =new Set(array)
set.add(newValue)
const toArr=Array.from(set)
localStorage.setImem("items",JSON.stringify(toArr))

unable to insert a new key value pair to the existing pair

We have name value pair field in our table.These field can be modified i.e either existing values can be changed or a new pair might get added .
We have written the below script to update existing values .
Please help on how to add ,new pair to the existing .
for (var name in u_service_characteristics) {
if (parsed.service_characteristics[name] != null &&
parsed.service_characteristics[name] != undefined) {
u_service_characteristics[name] = parsed.service_characteristics[name];
}
}
Above code only modifies the existing names ,how to insert if the incoming name doesnt exist.
I am guessing this is what you need
var existings = Object.getOwnPropertyNames(u_service_characteristics);
for (var name in parsed.service_characteristics) {
if (!existings.includes(name)) {
u_service_characteristics[name] = parsed.service_characteristics[name];
}
}
Instead of iterating over the keys of the target, just iterate over the keys of the source:
for(var name in parsed.service_characteristics)

Iterating over and comparing properties of two arrays of objects

I have set up a HBS helper which takes in two arrays of objects (users privileges). What I want to do is compare them and inject back into the template the privileges the user does and doesn't have.
Presently I can compare the names of the privileges with the following code:
hbs.registerHelper('selected', function(option, value){
var i;
var j;
var privName;
var userPriv;
var privObj = new Object();
var privArray = [];
for(i in option){
console.log('each ' + JSON.stringify(option[i]));
privName = option[i].privname;
for (y in value){
if(privName == value[y].privname){
userPriv = value[y].privname;
console.log('user has the following privileges', value[y].privname);
privObj = new Object();
privObj.name = userpriv;
privObj.id = value[y]._id;
privObj.state = 'selected';
privArray.push(privObj);
} else if (privName != value[y].privname){
console.log('user doesnt have priv ', privName);
privObj = new Object();
privObj.name = option[i].privname;
privObj.id = option[i].id;
privObj.state = '';
privArray.push(privObj);
}
}
}
console.log('privileges array ', privArray);
return privArray;
});
This works OK when the user only has one privilege, however when the user has more than one, for example two privileges, it returns the privileges twice. If the user has 3, thrice and so on. I know this is because the array is looping again because their are 2, 3 etc in the .length. However I can't seem to find an adequate solution.
Any help?
P.S. it would be nice if the Array.includes() method allowed you to search object properties.
The problem creating new objects the way you did is that for each property you add to your privilege-entity you will have to return to that function and set that property as well. You can instead just add/alter the state property of the existing objects:
hbs.registerHelper('selected', function(option, value) {
var names = option.map(function(opt) {
return opt.privname;
});
value.forEach(function(val) {
val.state = names.indexOf(val.privname) >= 0 ? 'selected' : '';
});
return value;
});
Basically:
The variable names is being mapped to be an array only with the privnames. You can check by using console.log(names).
The Array.forEach() function is helpful in this case because you just need to iterate over each object inside value and set its state-property.
To check if the privname exists, you just need to check the index in the previous names-mapped-array. For such a simple thing I used ternary operator (?:).
Finally, you return value, which is the array containing the objects you had updated.

Categories

Resources