I am trying to update a value in the array if it is found, if it isn't then add a new array to it.
Here's some code I have been trying:
var cartItems = {};
var items = []
cartItems.items = items;
$('.proAdd').click(function(){
var name = $(this).attr("data-name");
var price = parseFloat($(this).attr("data-price"));
var quantity = parseInt($(this).attr("data-quantity"));
var item = {"name": name,"price": price,"quantity": quantity}
items.forEach(function(item) {
if (item.name === name) {
item.quantity = 2
return;
}else{
cartItems.items.push(item);
}
});
In this version noting gets pushed. If I take out the else branch then it does update it but also pushes it. I have created a fiddle for this.
Also tried this but it says x.quantity is not defined:
var index = items.findIndex(x => x.name==name)
if (index != -1){
x.quantity = 2
}
else {
cartItems.items.push(item);
}
Because index stores the index of an item, and x is a temporary value which is unavailable after that line. Use find instead, and make sure you're looking at the same items each time:
var item = cartItems.items.find(x => x.name == name);
if (item) {
item.quantity = 2;
} else {
cartItems.items.push(item);
}
Related
I am building an e-commerece site with two pages and two Javascript files i.e:(index.html, cart.html, apps.js and cart.js). How do I subtract the total price that I had from the shopping cart (cart.html) when the remove button has been clicked?
This is my code:
// cart functionality
table.addEventListener("click", event => {
if (event.target.classList.contains('fa-close')) {
let removeItem = event.target;
console.log('df', removeItem);
let id = removeItem.dataset.id;
console.log(id);
table.removeChild(removeItem.parentElement.parentElement);
var obj = JSON.parse(localStorage.getItem("cart")) || {}; //fetch cart from storage
var items = obj || []; //get the products
for (var i = 0; i < items.length; i++) { //loop over the collection
if (items[i].id === id) { //see if ids match
items.splice(i, 1); //remove item from array
break; //exit loop
}
}
localStorage.setItem("cart", JSON.stringify(obj)); //set item back into storage
//decreasing the cart length
var cal = JSON.parse(localStorage.getItem('cart'));
if (cal.length != 0) {
cart_n.innerHTML = `[${cal.length}]`;
} else {
cart_n.innerHTML = '';
}
//subtractTotal cart
cal.find(item => {
tempTotal = 0;
tempTotal = item.price * item.id
})
row.innerHTML = tempTotal;
}
});
I've made a few comments in the code below based on what I believe you're trying to accomplish.
// cart functionality
table.addEventListener("click", event => {
// we can first check if the element does NOT (!) contain the class
// this means you don't need to wrap the remainder of the code
// as it will return early when the condition isn't met
if(!event.target.classList.contains('fa-close')){
return;
}
let removeItem = event.target;
console.log('df', removeItem);
let id = removeItem.dataset.id;
console.log(id);
table.removeChild(removeItem.parentElement.parentElement);
// should you be setting `obj` to `{}` here? (when it doesn't exist)
// you can't loop over an object the same way you loop over any array
// it looks like you should instead set it to `[]`
let obj = JSON.parse(localStorage.getItem("cart")) || {}; //fetch cart from storage
let items = obj || []; //get the products
for(let i = 0;i < items.length;i++) { //loop over the collection
if (items[i].id === id) { //see if ids match
items.splice(i, 1); //remove item from array
break; //exit loop
}
}
// you didn't modify `obj` in the previous loop, only `items`
// should you instead set this to `items` instead of `obj`?
// if the data exists in localStorage than you would be modifying
// `obj` directly but in the case it doesn't yet exist
// you will be returning a `{}` which cannot be looped over
// the same way you have above
localStorage.setItem("cart", JSON.stringify(obj)); //set item back into storage
// decreasing the cart length
let cal = JSON.parse(localStorage.getItem('cart'));
if(cal.length !== 0){
cart_n.innerHTML = `[${cal.length}]`;
}else{
cart_n.innerHTML = '';
}
// define tempTotal outside of the loop
let tempTotal = 0;
//subtractTotal cart
cal.find(item => {
// increment tempTotal by the price using `+=`
// I removed the `* item.id` as it doesn't make
// sense multiplying the `price` by the `id`
tempTotal += item.price;
// if the item has a `quantity` property
// you would use this code instead of the line above
tempTotal += item.price * item.quantity;
});
row.innerHTML = tempTotal;
});
What is the best way to search a particular parameter of an object array in Angular?
I populate my array from an Angular foreach :
$scope.arrayiwanttosearch = [];
angular.forEach(data, function(value, key) {
try{
var arrstring = new Array();
arrstring = value.img.split(',');
obj.name = value.name;
obj.selectedcolor = arrstring[0];
obj.colors = value.img;
obj.ischanging = false;
$scope.arrayiwanttosearch.push(obj);
}
catch(ex){
}
})
I can only use array.index of when its an array without objects, is there a way to do this without using a for loop? Im trying to find the index of the object that has the obj.name == "test"
Im trying to find the index of the object that has the obj.name ==
"test"
This is a straight use of findIndex.
var arrayiwanttosearch = [
{
name : "nottest"
},
{
name : "test"
}
];
var index = arrayiwanttosearch.findIndex(obj => obj.name === "test");
console.log(index);
You can use the native javascript 'filter' which will bring back all the matching members of the array, or 'find' which brings back the first one it finds, or 'findIndex';
// This finds the first matching array element with an object property === 2
$scope.arr = [{a:2,b:3}, {a:2,b:4}];
$scope.result = $scope.arr.find((item) => item.a === 2);
// The filter does the same but brings back all matching elements;
$scope.arr = [{a:2,b:3}, {a:2,b:4}];
$scope.result = $scope.arr.filter((item) => item.a === 2);
// The index result;
$scope.arr = [{a:2,b:3}, {a:2,b:4}];
$scope.result = $scope.arr.findIndex((item) => item.a === 2);
ES6 JS notation, but easy to adapt for ES5 JS.
You can use Array.prototype to get the index value in an array of objects.
var index = $scope.arrayiwanttosearch.indexOfname("test");
Array.prototype.indexOfname = function(name) {
for (var i = 0; i < this.length; i++)
if (this[i].name === name)
return i;
return -1;
}
I have an array with X number of items. Each has variables separated by a pipe character. In a loop I can split on the pipe to get the second item; but how do I splice to remove the duplicate.
"Sometext|22621086|address|333629dc87894a7ea7df5291fa6d1836|PC_E|1803"
"Sometext2|22622138|working|d3e70175ffe942568cd21f1cf96f4d63|PC_E|1803"
"Sometext3|22622138|working|851946e6325445da99c113951590f714|PC_E|1803"
Results should be this.
"Sometext|22621086|address|333629dc87894a7ea7df5291fa6d1836|PC_E|1803"
"Sometext2|22622138|working|d3e70175ffe942568cd21f1cf96f4d63|PC_E|1803"
Note that the duplicate 22622138 is a random number so the solution needs to work for any number in this location (it's always in the arr[1] position).
This is what I tried:
$.each(arr_transcript, function (i, e) {
if (e.length != 0) {
var arr = e.split("|")
var i = arr_transcript.indexOf(arr[1]);
if (i != -1) {
arr_transcript.splice(i, 1);
}
}
});
Here's a generic function:
function uniqBy(a, key) {
let seen = new Set();
return a.filter(item => {
let k = key(item);
return !seen.has(k) && seen.add(k);
});
};
var data = [
"Sometext|22621086|address|333629dc87894a7ea7df5291fa6d1836|PC_E|1803",
"Sometext2|22622138|working|d3e70175ffe942568cd21f1cf96f4d63|PC_E|1803",
"Sometext3|22622138|working|851946e6325445da99c113951590f714|PC_E|1803"
];
var result = uniqBy(data, item => item.split('|')[1]);
console.log(result)
See here for more info.
Create a map of the numbers you want to check against, and then filter based on that
var arr_transcript = [
"Sometext|22621086|address|333629dc87894a7ea7df5291fa6d1836|PC_E|1803",
"Sometext2|22622138|working|d3e70175ffe942568cd21f1cf96f4d63|PC_E|1803",
"Sometext3|22622138|working|851946e6325445da99c113951590f714|PC_E|1803"
];
var map = arr_transcript.map(function(text) {
return text.split('|')[1];
});
var filtered = arr_transcript.filter(function(item, index) {
return index === map.lastIndexOf( map[index] );
});
console.log(filtered)
I'm trying to set select a random item from an array. Once selected, it needs to be removed from the array so it does not get selected again. Finally, once the array is emptied, the process needs to restart. I'm trying to do this using sessionStorage because I need to keep track of which random item gets selected.
// Get array from sessionStorage
myArray = JSON.parse(sessionStorage.getItem("array"));
// If array does not exist in sessionStorage, set it
if (myArray === null) {
sessionStorage.setItem("array", JSON.stringify(["apple", "orange", "banana"]));
// If array exists in sessionStorage, use it to get random item and empty it from array
} else {
var randomItem = myArray[Math.floor(Math.random() * myArray.length)];
console.log(randomItem);
console.log(myArray.splice(randomItem, 1));
}
My JSFiddle can be seen here.
Edit: Updated my work here. Eventually the array is cleared out and restarts.
This probably will not run in this sandbox (use of localstore), but I think it should work if you tried it.
// -------------------------------
// see: http://stackoverflow.com/questions/2450954/how-to-randomize-shuffle-a-javascript-array
// -------------------------------
function _shuffle (array) {
for (var i = array.length - 1; i > 0; i--) {
var j = Math.floor(Math.random() * (i + 1));
var temp = array[i];
array[i] = array[j];
array[j] = temp;
}
return array;
}
// -------------------------------
// -------------------------------
// Get the next "random" item.
// -------------------------------
var randomItem = (function(allItems){
var _key = "array";
var _currentItems = [];
try {
_currentItems = JSON.parse(localStorage.getItem(_key) || "[]");
} catch (e) {
_currentItems = [];
}
if (!Array.isArray(_currentItems) || _currentItems.length === 0 ) {
console.log("resetting");
_currentItems = _shuffle(allItems.slice());
}
var _selectedItem = _currentItems.pop();
localStorage.setItem(_key, JSON.stringify(_currentItems));
return _selectedItem;
})(["apple", "orange", "banana"]);
// -------------------------------
console.log(randomItem);
A more bare bones version [ with _shuffle() from above ] might be just:
var nextItem = (function(all){
var _key = "array";
var _current = JSON.parse(localStorage.getItem(_key) || "[]");
if (_current.length === 0) { _current = _shuffle(all.slice()); }
var _selected = _current.pop();
localStorage.setItem(_key, JSON.stringify(_current));
return _selected;
})(["apple", "orange", "banana"]);
I think the problem you are having is caused by the fact that you are passing the value you get from the array the the splice() function when it is actually expecting an index. Checkout the docs page. so what you would do instead is:
// Get array from sessionStorage
myArray = JSON.parse(sessionStorage.getItem("array"));
// If array does not exist in sessionStorage, set it
if (myArray === null) {
sessionStorage.setItem("array", JSON.stringify(["apple", "orange", "banana"]));
// If array exists in sessionStorage, use it to get random item and empty it from array
} else {
//get random index of item to remove
var randomIndex = Math.floor(Math.random() * myArray.length);
//remove the item at that index
myArray.splice(randomIndex, 1); //this returns an array containing the removed item, so you can capture it if you like
}
i'm having trouble to remove duplicated object from my array
example:
var list = [{place:"AAA",name:"Me"}, {place:"BBB",name:"You"}, {place:"AAA",name:"Him"}];
in this example i have 3 objects, and i want to remove the object that have the duplicated place
Just in case someone wonders: underscore.js solution:
var list = [{place:"AAA",name:"Me"}, {place:"BBB",name:"You"}, {place:"AAA",name:"Him"}];
_.uniq(list, function(item, key, a) {
return item.place;
})
Example Fiddle
A simple one:
var list = [{place:"AAA",name:"Me"}, {place:"BBB",name:"You"}, {place:"AAA",name:"Him"}];
list.forEach(function(i) {
var duplicates = list.filter(function(j) {
return j !== i && j.place == i.place;
});
duplicates.forEach(function(d) { list.splice(list.indexOf(d), 1); });
});
// list = [{place:"AAA",name:"Me"}, {place:"BBB",name:"You"}];
document.write(JSON.stringify(list));
As you added:
i want to remove just one, dont matter wich one
If you want to remove duplicated items and keep only the first occcurence of particular place, you can simply use a simple loop to re-create a new array from the input:
var list = [{place:"AAA",name:"Me"}, {place:"BBB",name:"You"}, {place:"AAA",name:"Him"}];
var uniqPlace = function(array){
var result = [];
array.forEach(function(el){
if (result.filter(function(n){ return n.place === el.place }).length==0){
result.push(el);
}
})
return result;
}
Output:
uniqPlace(list);
[{"place":"AAA","name":"Me"},{"place":"BBB","name":"You"}]
Try this.
var result = {};
for (i = 0, n = arr.length; i < n; i++) {
var item = arr[i];
result[ item.place + " - " + item.name ] = item;
}
Loop the result again, and recreate the array.
i = 0;
for(var item in result) {
clearnArr[i++] = result[item];
}
Create a object to store the items by their place value, as the new item with the same key will overwrite the old one, this will easily remove all dulplicates.
var list = [{place:"AAA",name:"Me"}, {place:"BBB",name:"You"}, {place:"AAA",name:"Him"}];
var removeDuplicate = function(list) {
var keyStore = {};
var output = [];
// If you want to creata totally new one from old, use
// list = JSON.parse(JSON.stringify(list));
// The above commented out code will create a copy of list, so the items in output will not affect the original ones.
list.forEach(function(item) {
// new one overwrites old one.
keyStore[item.place] = item;
});
var key;
for (key in keyStore) {
output.push(keyStore[key]);
}
return output;
};
console.log(removeDuplicate(list));
3 way to remove duplicate objects from array
let list = [{place:"AAA",name:"Me"},
{place:"BBB",name:"You"},
{place:"AAA",name:"Him"}];
let output1 = Array.from(new Set(list.map(list=>list.place))).map(place=>{
return {
place: place,
name: list.find(a=>a.place===place).name
}
})
console.log('------------------------1st way')
console.log(output1)
let output2 = list.reduce((accumulator, element) => {
if (!accumulator.find(el => el['place'] === element['place'])) {
accumulator.push(element);
}
return accumulator;
},[]);
console.log('------------------------2nd way')
console.log(output2)
const output3 = [];
const map = new Map();
for (const object of list) {
if(!map.has(object.place)){
map.set(object.place, true);
output3.push({
place: object.place,
name: object.name
});
}
}
console.log('------------------------3rd way')
console.log(output3)