How to push object from oner array to another? - javascript

I have two arrays now once i rendered the data from backend i want to push just object from array2 to array1 not the array itself.
How can i just push object from array2 to array1 I dont want to push as array.
ctrl.js
var array1 = [{name:'john', address:'cliffwood ave'}]
var array2 = [{name:'Mike', address:'florence ave'}]
array1.push(array2);

If you want to mutate array1:
array1.push.apply(array1, array2);
Otherwise:
var array3 = array1.concat(array2);

If you wanted to push a single object in the array, you could just reference it by it's specific index :
array1.push(array2[0]);
Otherwise, if you wanted to push all of the items, you might consider just concatenating them via the concat() function :
array1.concat(array2);

If you want to use ES6 you can use the spread operator:
array1.push(...array2);
which is functionally equivalent to this ES5 method...
array1.push.apply(array1, array2);
...mentioned in one of the other answers.
DEMO

To push {name:'Mike', address:'florence ave'} into array1 :
array1.push(array2[0]);
As the object you want is simply the first element in your array2 variable.

(var I = 0; I <= array2.length-1 ; I++){
array1.push(array2[I])
}

Related

Check if an array of arrays contains a value in javascript

I know that if there is an array of values it must be used this approach:
console.log(['joe', 'jane', 'mary'].includes('jane')); // true
But in case of an array of arrays, is there a short way to do it? Without other computations between.
For this input:
[['jane'],['joe'],['mary']]
You can use flat method to flatten the array. For more neted array, you can also mention depth like flat(depth)
let arr = [["jane"],["joe"],["mary"]];
arr.flat().includes('jane'); //true
You can easily achieve this result using some
arr.some((a) => a.includes("jane"))
const arr = [
["jane"],
["joe"],
["mary"]
];
const arr2 = [
["joe"],
["mary"]
];
console.log(arr.some((a) => a.includes("jane")));
console.log(arr2.some((a) => a.includes("jane")));
it can also be done by first flattening the 2d arrays in 1 d aaray and then using includes to find whether the array contains the element or not
var arr = [['jane'],['joe'],['marry']]
var newarr=[].concat(...arr)
var v=newarr.includes('jane')
console.log(v)

Is it possible to add an array into another array

I need to add ann array to an existing array.
If i have an array
var array = ["foo", "baah"];
then, what i need to do is to add an array into the existing one. So it ends up looking like
var array = ["foo", "baah", ["newfoo", "newbaah"]];
i need to do it client site, so using javascript or JQuery. Anyone who can help me? If i can't add a array to a array, is i then possible to add an object
Something like
var array = ["foo", "baah", /*myObject containing 2 item*/];
just ask for more info if needed.
Just .push will do it
var array1 = ["foo", "baah"];
var array2 = ["newfoo", "newbaah"];
array1.push(array2)
console.log(array1)
const arrOne = [1,2,3];
const arrTwo = [4,5];
arrOne[arrOne.length] = arrTwo;
console.log(arrOne);
You don't need to use .push(), you can use index notation.
Just use push:
var array1 = ["foo", "baah"];
var array2 = ["newfoo", "newbaah"];
array1.push(array2);
console.log(array1);
You can do it via ... spread operator.
var array1 = ["foo", "baah"];
var array2 = ["newfoo", "newbaah"];
var array3 = [...array1, array2];
console.log(array3);
.push will mutate your first array but this one doesn't.
Push
You can use push to add one array to another
var a = [1,2]
var b =[3,4]
a.push(b) //[1,2,[3,4]]
unshift
This is similar to push but adds the array to the first
a.push(b) //[[3,4],1,2]
concat
a.concat(b)//[1,2,3,4]
concat returns a new array rather than push and unshift which adds in the existing array

How can i merge two different array of object with having one same key value

I want to merge two different array of objects which having one same key value.
here are my two array of objects.
arr1 = [{id:1,name:'amit',age:23},{id:2,name:'akash',age:24},{id:3,name:'arun',age:22}];
arr2 = [{id:1, add : 'india'},{id:3, add:'india'},{id:2,add:'india'}];
I want to merge these two array into one array with complete data .
arr3 = [{id:1,name:'amit',age:23, add:'india'},{id:2,name:'akash',age:24, add:'india'},{id:3,name:'arun',age:22,add:'india'}];
i try to do this but could not get the desired result.
var arr3 = _.map(arr1, function(item){
return _.extend(item, _.findWhere(arr2, { id: item.id }));
});
there can be some empty array which can cause changes.
i want to avoid two for loops and then one if condition because it will increase complexity. if anyone have better solution for this.
thanks in advance.
This will give the desired result.
_.each will iterate the arr3 and perform the action.
// copies arr1 to arr3
var arr3 = Array.from(arr1);
_.each(arr3, (item) => {
// extends another object to the current object (item from arr3)
_.extend(item, _.find(arr2, (a) => a.id == item.id));
})
We will get the desired result in arr3
You can use loadash merge
var arr3 = _.merge(arr1, arr2)

Pushing a value to an array of objects

I can't seem to figure out as to why I am unable to append a value to my array below? Is there a special syntax to follow or something when constructing an array like in the method used below?
var arr = {
"fruits": ['apple','banana','orange']
};
arr.push({ "fruits":"testing123"}); // This line fails
alert(arr["fruits"]);
Try: arr.fruits.push("mango");
You can't push() to an object. You should either use the key-value notation:
arr.anotherFruits = "testing123"; // another key
arr.fruits = "testing123"; //to overwrite
Or make arr actually array:
var arr = [
{"fruits": ['apple','banana','orange']}
]
arr.push({ "fruits":"testing123"})
alert(arr["fruits"])
In this case you'd get
var arr = [
{"fruits": ['apple','banana','orange']},
{"fruits":"testing123"}
]
Or in case you did want to get an object like this
var arr = {
"fruits": ['apple','banana','orange','testing123']
}
you should've used arr.fruits.push('testing123');
Your array defintion is all wrong. Assuming you want arr to be an object that has an array under fruits and then push another value inside fruits, use the following:
var arr = {
fruits: ['apple', 'banana', 'orange']
};
arr.fruits.push("testing123");
console.log(arr["fruits"]);
Change your initial arr declaration to this...
var arr = [{
"fruits": ['apple','banana','orange']
}];
Then you can push more objects onto it. E.g.
arr.push({"fruits": ['mango', 'pear', 'tomato']});
Or, if you wish to push fruits to the existing array INSIDE your object, then simply use your existing arr declaration and use it like this...
arr.fruits.push('tomato');
arr.fruits.push('pear');
arr.fruits.push('tomato');
I'd argue that you don't really require this to be an object at all here.
All you need is this...
var fruits = [];
fruits.push('banana');
fruits.push('apple');
It's simply an array of fruits. If you need more complex structure, then use an array of objects, instead of strings.
Array has push() method, but Object does not. Here you create an Object, but not an Array. So it failed.

How to use push with sub-arrays?

I have 3 arrays like:
var arr1 = [];
var arr2 = [];
var arr3 = [];
//When I want to add something into array then I use
arr1.push("text");
arr2.push("text");
but is it possible to make something like the following example?
//example:
var arr = [];
arr['group1'].push("text1");
arr['group2'].push("text2");
arr['group2'].push("textn");
//and then iterate like:
for(item in arr['group1'])
console.log(item);
is it even possible to do something like that? I have tried but does not work.
There's a fundamental misunderstanding though, arr is an array but you're using it as an associative array, which in JavaScript is better represented with an object {}. for...in is for objects, NOT arrays, the MDN has a warning note about it:
for..in should not be used to iterate over an Array where index order
is important...
I would advice even if index is trivial to use a regular for loop or a forEach.
Consider using the following, more appropiate approach.
var obj = {
group1: ['text1'],
group2: ['text2'],
group3: ['text3']
};
// pushing more strings
obj.group1.push('foo');
obj['group2'].push('baz');
You're treating arr['group1'] as an array (by using .push()), but you haven't declared it as an array.
var arr = [];
arr['group1'] = [];
arr['group2'] = [];
arr['group3'] = [];
arr['group1'].push("text1");
arr['group2'].push("text2");
arr['group2'].push("textn");
It seems you're actually looking for Javascript Objects instead of arrays.
Also, you need to create these objects first.
var obj = {group1:[],group2:[],group3:[]};
/* or
var obj = {};
obj.group1 = [];
*/
obj['group1'].push("text1");
// or obj.group1.push("text1");
The for...in structure sets your for variable to the key, not the value. Assuming arr['group1'] is an array, this will work fine:
//example:
var arr = [];
arr['group1'].push("text1");
arr['group2'].push("text2");
arr['group2'].push("textn");
//and then iterate like:
for(item in arr['group1'])
console.log(arr['group1'][item]);​

Categories