Javascript .push causing array to nest deeper and deeper [duplicate] - javascript

This question already has answers here:
How to extend an existing JavaScript array with another array, without creating a new array
(20 answers)
Copy array items into another array
(19 answers)
Closed 3 years ago.
I'm sure this is an easy one, however my searches haven't helped as of yet.
When I push an array into another array, they nest a level deeper. The first array is at the correct depth.
var productArray = [{productID: currentProduct, productPrice: currentPrice, productName: productName, options: myOptions}];
if(localStorage.getItem("cart")){
var existingArray = JSON.parse(localStorage.getItem("cart"));
existingArray.push(productArray);
localStorage.setItem("cart", JSON.stringify(existingArray));
} else {
localStorage.setItem("cart", JSON.stringify(productArray));
}
Result:
0: Object { productID: "1", productPrice: "2.00", productName: "Chicken Sandwich", … }
​
1: 0: Object { productID: "1", productPrice: "2.00", productName: "Chicken Sandwich", … }
​
2: 0: Object { productID: "1", productPrice: "2.00", productName: "Chicken Sandwich", … }

You have multiple options to concatenate two arrays, but .push is not it (unless you iterate the 2nd array and push each element individually, OR followup with .flat())
let array = [1, 2, 3];
array.push([4, 5, 6]);
console.log(array); // [1, 2, 3, [4, 5, 6]]
array = array.concat([7, 8, 9]);
console.log(array); // [1, 2, 3, [4, 5, 6], 7, 8, 9]
array = [...array, ...[10, 11, 12]];
console.log(array); // [1, 2, 3, [4, 5, 6], 7, 8, 9, 10, 11, 12]
array.push(13, 14, 15);
array = array.flat();
console.log(array); // [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]

Because productArray is an array, and not an object, pushing it into another array will create another array, which will contain both, the initial array, and the new one.
To do what you were expecting, you should declare a new object, and push it into the existing array.
var productObject = {productID: 1, productPrice: 1, productName: '', options:{}};
var productArray = [];
if(localStorage.getItem("cart")){
var existingArray = JSON.parse(localStorage.getItem("cart"));
existingArray.push(productObject );
localStorage.setItem("cart", JSON.stringify(existingArray));
} else {
productArray.push(productObject);
localStorage.setItem("cart", JSON.stringify(productArray));
}

I think you are adding the entire "productArray" in the position n of your "existingArray". Try to make this.
var productArray = [{productID: currentProduct, productPrice: currentPrice, productName: productName, options: myOptions}];
if(localStorage.getItem("cart")){
var existingArray = JSON.parse(localStorage.getItem("cart"));
productArray.forEach(function(val){
existingArray.push(val);
})
localStorage.setItem("cart", JSON.stringify(existingArray));
} else {
localStorage.setItem("cart", JSON.stringify(productArray));
}

Related

Hoow to remove Items from the Array dynamically?

I need a function which removes some items from array dynamically.
for example:
const array = [1, 2, 3, 4, 6, 1, 3, 9, 5, 7, 6, 8, etc.];
I need to remove all items before item "6", but after remove it stop the function and don't remove next items before next item "6".
There are word's array in project and I need to filter it. need to remove all items before one specific word.
findIndex and slice will do it
const array = [1, 2, 3, 4, 6, 1, 3, 9, 5, 7, 6, 8];
const findNum = 6;
const idx = array.findIndex(num => num === findNum)
console.log(array.slice(idx))

Relative Sort Array Javascript

I am working on a problem on LeetCode and having some troubles
https://leetcode.com/problems/relative-sort-array/
Instructions:
Given two arrays arr1 and arr2, the elements of arr2 are distinct, and all elements in arr2 are also in arr1.
Sort the elements of arr1 such that the relative ordering of items in arr1 are the same as in arr2. Elements that don't appear in arr2 should be placed at the end of arr1 in ascending order.
Example 1:
Input: arr1 = [2,3,1,3,2,4,6,7,9,2,19], arr2 = [2,1,4,3,9,6]
Output: [2,2,2,1,4,3,3,9,6,7,19]
my attempt:
var relativeSortArray = function(arr1, arr2) {
let arr =[]
let end =[]
for (i=0; i<arr2.length; i++){
for (j=0; j<arr1.length; j++){
if(arr2[i] == arr1[j]){
arr.push(arr1[j])
}else{
end.push(arr1[j])
}
}
}
end.sort((a,b) => a-b)
console.log(end)
return arr
};
The If conditional works but the else condition isn't and I can't figure out why.
I think console.log(end) should give me the two numbers not in arr2 but it instead gives me:
[
1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3,
3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 6,
6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 9, 9,
9, 9, 9, 19, 19, 19, 19, 19, 19
]
Why is this happening?
Thanks!!!
You could take an object for the position of a value and take a large value like Number.MAX_VALUE as default value. If the delta is zero sort by value.
Taking a delta is a standard by using Array#sort. This returns a value smaller than zero, zero or greater than zero, depending on the values. The sort method receives this values and keeps or swaps the values.
const
relativeSort = (array, given) => {
const order = Object.fromEntries(given.map((v, i) => [v, i + 1]));
return array.sort((a, b) =>
(order[a] || Number.MAX_VALUE) - (order[b] || Number.MAX_VALUE) ||
a - b
);
};
console.log(...relativeSort([2, 3, 1, 3, 2, 4, 6, 7, 9, 2, 19], [2, 1, 4, 3, 9, 6]));
In each iteration of arr2:
all the numbers that are different from the current number are pushed to the end array
For example,
First iteration - compare number (2) and you will end up with:
arr: [2,2,2]
end: [3,1,3,4,6,7,9,19]
Second iteration - compare number (1) and you will end up with:
arr: [2,2,2,1]
end: [3,1,3,4,6,7,9,19] + [2,3,3,2,4,6,7,9,2,19]
try to debug your code to follow the flow
class Solution:
def relativeSortArray(self, arr1: list[int], arr2: list[int]) -> list[int]:
arr = []
for i in arr2:
value = arr1.count(i)
for j in range(value):
arr.append(i)
arr1.remove(i)
arr1.sort()
return arr+arr1
obj = Solution()
arr1 = [28,6,22,8,44,17]
arr2 = [22,28,8,6]
result = obj.relativeSortArray(arr1,arr2)
print(result)

Create a sorted array by mistake using .map()

I tried to make something that works as Set() using a couple tools that I learned. It worked, but I noticed a bug: it sorted my array! Can explain me someone why, please?
Here's my code:
function uniteUnique(...arr) {
let array = arr.flat()
let newArr = [];
console.log(array) // [ 1, 3, 2, 5, 2, 1, 4, 2, 1 ]
let myMap = array
.map(elem => {
if (!newArr.includes(elem))
return newArr.push(elem)
})
.filter(Boolean)
console.log(myMap) // [ 1, 2, 3, 4, 5 ]
}
uniteUnique([1, 3, 2], [5, 2, 1, 4], [2, 1]);
I know that for you might be too simple, but I ask so I can understand what is happening here.
console.log(myMap) // [ 1, 2, 3, 4, 5 ]
The result of your log is the number of pushed elements but accidentally, you thought they are sorted.
Also, if you return the mapped list you will end up with an array that contains an integer and boolean values. Instead of this, you need to return newArr.
Your code will be like this :
function uniteUnique(...arr) {
let flattedArray = arr.flat()
let set = [];
flattedArray.forEach(elem => !set.includes(elem) && set.push(elem))
return set
}
const set = uniteUnique([1, 3, 2], [5, 2, 1, 4], [2, 1]);
console.log(set)
in your code MyMap holds your newArr length as array.push returns the length of your array
so every time it returns the count:
for example if you tried to run this code
let newArr = []
console.log(newArr.push(20)) // the output is 1
and that's what your myMap holds => the length of your newArr
so if you want the filtered array you should use newArr
let array = [ 1, 3, 2, 5, 2, 1, 4, 2, 1 ]
let newArr = [];
let myMap = array.map(elem => {
if (!newArr.includes(elem))
return newArr.push(elem)
}).filter(Boolean)
console.log(newArr) //[1, 3, 2, 5, 4]

Push duplicate values to another array in JavaScript

I have an array, which contains duplicate values. How can I push duplicates in to another array?
let arr1 = [1, 5, 3, 6, 9, 5, 1, 4, 2, 7, 9], and duplicates array should be dupArr = [1, 5, 9]
You could filter the array by storing the previous checked values in a Set, which is here a closure.
var array = [1, 5, 3, 6, 9, 5, 1, 4, 2, 7, 9],
duplicates = array.filter((s => v => s.has(v) || !s.add(v))(new Set));
console.log(duplicates);

How to sort javascript set array when we getting diffrent type of array everytime

var array = [355, 1, 488, 6, 4, 78, 63, 4, 3, 1];
// array = [9, 2, 5, 4, 6],
// array = ["1001", "25", "36", "25"],
// array = ["c1-ca-10-1a-11-f4","c1-ca-10-1a-11-f5","c1-ca-10-1a-11-f1" //];
assetData = new Set();
array.forEach(function(data) {
assetData.add(data);
});
assetData = Array.from(assetData)
assetData.sort(function() {
return 0.5 - Math.random();
});
console.log(assetData);
var newArray = [];
Array.prototype.push.apply(newArray, assetData
);
In above code i want to sort all arrays.i have 4 type of array i need to sort all of them.
Below is the best way to handle all kind of array element sorting.
var //array = [355, 1, 488, 6, 4, 78, 63, 4, 3, 1];
// array = [9, 2, 5, 4, 6],
//array = ["1001", "25", "36", "25"],
array = ["c1-ca-10-1a-11-f4","c1-ca-10-1a-11-f5","c1-ca-10-1a-11-f1"];
assetData = new Set();
array.forEach(function(data) {
assetData.add(data);
});
assetData = Array.from(assetData)
assetData.sort(function(a, b){return a-b});
console.log(assetData);
var newArray = [];
Array.prototype.push.apply(newArray, assetData
);

Categories