Im trying to push my array of objects into variable, but all i I recieve is Array in Array, or single object.
myObject = {
id: id,
items: [],
boolean: true,
}
myArray = [{1}, {2}, {3}]
I tried myObject.items.push(myArray[0]) but this returns only first object. Without 0 its double array.
What i want is
myObject = {
id: id,
items: [{1}, {2}, {3}],
boolean: true,
}
What you're going to want to do here is set the entire array as the new value like this:
myObject.items = myArray
If you want to take the immutable approach then you can copy it like this:
myObject.items = [...myArray]
Edit:
If you want to add items (and not just complete overwrite) to myObject.items then you should do this:
myObject.items = [...myObject.items, ...myArray]
That will add your new array items to the end of the current items array, you could also do this to add them to the start:
myObject.items = [...myArray, ...myObject.items]
you can use this
myObject.items.push(...myArray)
As Andreas commented another solution is to use concat. Concat is similar to push. But it doesn't actually change the array it returns a new one.
const x = []
console.log(x.concat(3)) // prints [3]
console.log(x) // prints []
This behavior is often desired as it prevents "side effects" from occurring
It also doesn't just append items to an array, it only does this if the item is not an array. If it is an array it will merge the two arrays
const x = [1,2,3]
console.log(x.concat([4,5,6]) // prints [1,2,3,4,5,6]
so a solution here is
myObject.items = myObject.items.concat(myArray)
//object
myObject={
id:1,
items:[],
boolean: true
}
//concat
myArray = [ 1,2,3];
myObject.items += myArray;
console.log(myObject.items);
Related
I have two arrays and I would like to compare if these arrays have duplicated values, then return the values that aren't duplicates. Based on these two arrays I would like to return the string Eucalipto.
const plants = [
{
id: 59,
kind: "Cana-de-açucar"
},
{
id: 60,
kind: "Citros"
}
];
const auxPlants = [
"Cana-de-açucar",
"Citros",
"Eucalipto"
]
You can use Array#map to find all the kind values, pass that to the Set constructor, and then use Array#filter to find all elements of the array not in that Set.
const plants = [
{
id: 59,
kind: "Cana-de-açucar"
},
{
id: 60,
kind: "Citros"
}
];
const auxPlants = [
"Cana-de-açucar",
"Citros",
"Eucalipto"
];
const set = new Set(plants.map(({kind})=>kind));
const res = auxPlants.filter(x => !set.has(x));
console.log(res);
sounds like you want to filter the array of values you're interested in based on if they're not found in the other array, like so:
const nonDuplicates = auxPlants.filter(a => !plants.find(p => p.kind === a))
it's unclear if you'd also want values from the plants array that are non duplicate as well, or if you're only interested in uniques from the auxPlants array
This is the solution to it, I have explained it's working using comments
// create a set in order to store values in it
// assuming you have unique values
let set = new Set();
// iterating over array of object and storing the value of 'kind' in the set
for(obj of plants){
set.add(obj.kind);
}
// iterating over array and checking for values in set,
// if not in set then printing it
for(ele of auxPlants){
if(!set.has(ele)){
console.log(ele);
}
}
As said, please search for an already posted solution first. Here's what I found.
Anyhow, the solution would be to separate the types of plants from the first array, as so:
const plantsTypes = plants.map(obj => obj.kind)
Then, filter out the non duplicates:
const nonDuplicates = auxPlants.filter(plant => !plantsTypes.includes(plant))
Note that it matters which array you call the .filter() function on.
I have two array called 'persons' and 'persons2',
The 'persons2' array would to be copy of 'persons' array,
But the problem is when I copy it, and I want to change the second array, the first array is also changing. This is my code:
export class AppComponent {
persons = [
{
name:'David',
lname:'Jeu'
}
];
persons2=[...this.persons];
constructor(){
console.log(this.persons[0]);
this.persons2[0].name='Drake';
console.log(this.persons[0]);
console.log(this.persons2[0]);
}
}
But the problem is when I copy it, and I want to change the second
array, the first array is also changing
That is because the objects inside both the arrays are sharing same reference. To perform a deep copy try the following :
let persons2 = person.map(x => Object.assign({}, x));
Or
let person2 = JSON.parse(JSON.stringify(person));
In your case both the array is referring to the same memory, which is commonly known as shallow copy.
You can make a deep copy of the first array and then change the second array. That will have no impact on the first array.
let persons = [{
name: 'David',
lname: 'Jeu'
}];
let persons2 = JSON.parse(JSON.stringify(persons));
persons2[0].age = 29;
console.log(persons)
console.log(persons2)
For these kinds of operations it is usually wise using Lodash Clonedeep
I created an array with many elements with a loop:
myArray = [c1, c2, c3...]
now I want to make each element into an object and assign different key values:
c1 = {image = path, value = number)
I tried to run forEach() but can't figure out the correct way to do so and I have not succeeded in finding the answer to it.
My guess was:
myArray.forEach(function() {
let name = {
image = path,
value = number,
}
return name;
});
but there's no change in the elements in the log.
Any help or link to an answer that can help me here. First time coding here.
UPDATE: an easier solution was to .push all the keys and values of the objects when I created the array with the loop in the first place.
array.push({image: pathx, value: numberx})
You can, but you'd be better off with a simple for loop:
for (let i = 0; i < myArray.length; ++i) {
let entry = myArray[i];
myArray[i] = {image: entry.path, value: entry.number};
}
Or making a new array with map.
newArray = myArray.map(entry => ({image: entry.path, value: entry.number}));
Or if you prefer non-arrow functions:
newArray = myArray.map(function(entry) {
return {image: entry.path, value: entry.number};
});
You could theoretically push to a new array but this is the exact usecase for Array#map. Array#map maps old values to new values. The returned object from the callback is the new object and the returned array is the new array containing the new objects.
Semantically, Array#forEach is to plainly iterate over each element in an array, and possibly execute something with side-effects (which may include pushing to another array). But with Array#map, it's specifically used to transform old array values to new ones. Use the one that is specifically designed because it conveys a clear message to anyone else who reads your code.
const newArray = myArray.map(({ path, number }) => ({
image: path,
value: number
}));
Array#map maps old values to new values. You may need to use the follwing instead of arrow functions as it is not supported in IE.
I just added dummy data in the object, you can change it.
myArray = ["c1", "c2", "c3"]
myArray = myArray.map(function(elem) {
return {"image":"path"+elem,"value":"value"+elem};
});
console.log(myArray);
I'm trying to create a copy of existing array and remove some items from array copy without impacting the original. I've tried this :
var new_arr = old_arr; //when I remove from new array the items from old array are also removed
How do I create entirely new copy of the existing array?
Update :
When I do this :
var new_arr = old_arr.slice();
then later :
new_arr[0].shift();
new_arr[1].shift();
The items from old_array get removed. This is a two dimensional array.
You can use two methods, this:
function clone (src) {
return JSON.parse(JSON.stringify(src));
}
or this:
var newArray = oldArray.slice();
A newer solution to do this is to use 'from' like this:
const newArr = Array.from(oldArr);
But this is a shallow copy and if nested elements are mutated they will project in the new created array with from. Best solution then would be to use
const newArr = JSON.parse(JSON.stringify(oldArr));
but also that method doesn't ensure all. If for example an element of the array contains a function like n => ++n then it will be null after using the JSON methods so best solution is deepClone and for that full explanation I refer to
Creating JavaScript Arrays
Using Yoshi answer you can extend Array prototype (just a simple helper):
Array.prototype.clone = function() {
return this.slice(0);
}
In Javascript, a two-dimensional array is just an array of arrays. Therefore, cloning one dimension is not enough. We also need to clone all the sub-dimension arrays. Here’s how we do it:
function cloneGrid(grid) {
// Clone the 1st dimension (column)
const newGrid = [...grid]
// Clone each row
newGrid.forEach((row, rowIndex) => newGrid[rowIndex] = [...row])
return newGrid
}
// grid is a two-dimensional array
const grid = [[0,1],[1,2]]
newGrid = cloneGrid(grid)
console.log('The original grid', grid)
console.log('Clone of the grid', newGrid)
console.log('They refer to the same object?', grid === newGrid)
---
The original grid [ [ 0, 1 ], [ 1, 2 ] ]
Clone of the grid [ [ 0, 1 ], [ 1, 2 ] ]
They refer to the same object? false
Or if we take avantage of ES6 Array.map operation, we can make cloneGrid function even simpler:
const cloneGrid = (grid) => [...grid].map(row => [...row])
For more expanded answer read How to make a copy of an array in JavaScript
You can try .concat()
var old_arr = [1,2,3,4,5]
var new_arr = old_arr.concat()
console.log(old_arr) //1,2,3,4,5
console.log(new_arr) //1,2,3,4,5
new_arr.shift()
console.log(old_arr) //1,2,3,4,5
console.log(new_arr) //2,3,4,5
you may create a new array by using the spread operator. You can also find more about spread operator HERE.
cosnt oldArr = [{id: 1, name: 'Ali'}, {id:2, name: 'Raza'}];
cosnt newArray = [...oldArr];
console.log(newArray);
I have data being pulled in from various sources, each returning some form of JSON or similar, although, differently formatted each time. I need to get them all into one array, but I can't figure out how to do it.
The first set is an array like this:
[
Object {id="70", type="ab", dateadded="12345678"},
Object {id="85", type="ab", dateadded="87654321"}, ... more items ...
]
The second set is being pulled in from Facebook, and is like this:
[
Object {id="12341234234", created_time="12345678"},
Object {id="567856785678", created_time="87654321"}, ... more items ...
]
So, I need to alter the second set so that it has 'type', and it has 'dateadded' instead of 'created_time', and then I need to get this all into one array so it can be sorted on 'dateadded'.
How can I do this?
Use the first array's push() method:
// for each item in second array
firstArray.push(convert(item));
function convert(obj) {
// Convert obj into format compatible with first array and return it
}
Hope this helps.
Assuming you have actual valid JSON instead of what you quoted above:
var jsonOld = '[{"id":"70","type":"ab","dateadded":"12345678"},{"id":"85","type":"ab","dateadded":"87654321"}]',
jsonNew = '[{"id":"12341234234","created_time":"12345678"},{"id":"567856785678","created_time":"87654321"}]';
Then first parse these values into actual Javascript arrays:
var mainArr = JSON.parse(jsonOld),
newArr = JSON.parse(jsonNew);
(If you already have actual Javascript arrays instead of JSON strings then skip the above step.)
Then just iterate over newArr and change the properties you need changed:
for (var i = 0, il = newArr.length; i < il; i++) {
newArr[i].type = 'ab';
newArr[i].dateadded = newArr[i].created_time;
delete newArr[i].created_time;
}
And concatenate newArr into mainArr:
mainArr = mainArr.concat(newArr);
And sort on dateadded:
mainArr.sort(function(a, b) { return a.dateadded - b.dateadded; });
This will result in:
[{"id":"70","type":"ab","dateadded":"12345678"},
{"id":"12341234234","type":"ab","dateadded":"12345678"},
{"id":"85","type":"ab","dateadded":"87654321"},
{"id":"567856785678","type":"ab","dateadded":"87654321"}]
See example