how to push an element at index 0 of an array [duplicate] - javascript

This question already has answers here:
How to insert an item into an array at a specific index (JavaScript)
(28 answers)
Closed 6 years ago.
i have a situation like this,
i have 2 array1 as array1 = ["fruit","vegetables"];
and
array2 = [["apple","banana"],["tomato"]]; // index 0:represent fruit i,e (["apple","banana"]), index 1: vegetables i,e (["tomato"])
my question : how can i push item from array1 so as to make my array2 look like this
[["fruit","apple","banana"],["vegetables","tomato"]];
with that i can determine index:0 as category.
MY data structure is these 2 array array1 = ["fruit","vegetables"]; AND array2 = [["apple","banana"],["tomato"]];
if i'm able to get key value pair array that would good for me.
my sample data:
array1 = ["fruit","vegetables"];
array2 = [["apple","banana"],["tomato"]]; //expected output :[["fruit","apple","banana"],["vegetables","tomato"]];

Use Array#unshift method.
var array1 = ["fruit", "vegetables"],
array2 = [
["apple", "banana"],
["tomato"]
];
var array3 = array2.map(function(v, i) { // iterate over the array to generate the new array
var arr = v.slice(); // copy the array
arr.unshift(array1[i]) // insert element at beginning
return arr; /// return generated array
});
console.log(array3)
UPDATE : If you don't want to create a new array then you can avoid the copying part.
var array1 = ["fruit", "vegetables"],
array2 = [
["apple", "banana"],
["tomato"]
];
array2.forEach(function(v, i) { // iterate over the array
v.unshift(array1[i]) // insert element at beginning
});
console.log(array2)
With ES6 arrow function :
var array1 = ["fruit", "vegetables"],
array2 = [
["apple", "banana"],
["tomato"]
];
array2.forEach((v, i) => v.unshift(array1[i]));
console.log(array2)

Try this Array.map() and Array.unshift() .unshift() push the data into array [0]index position.
array1 = ["fruit","vegetables"];
array2 = [["apple","banana"],["tomato"]];
array2.map((a,i) => a.unshift(array1[i]))
console.log(array2)

Related

Splitting array into multiple arrays

I have looked up answers on these questions
How to split a long array into smaller arrays, with JavaScript
and Split array into chunks but i still do not understand what i am doing wrong.
I have multiple random arrays that look like this
['dog']
['dog', 'cat']
['cat', 'apple', 'frog']
['apple', 'dog']
etc.
and i want to split them so they look like this
['dog']
['dog'] ['cat']
['cat'] ['apple'] ['frog']
['apple'] ['dog']
I was wondering if i could use a foreach loop to loop through all the arrays and split them into single arrays.
this is what my code looks like
var arrays = press.post_category;
arrays.forEach(function(item){
var arr = [];
var size = 1;
for (let i = 0; i < item.length; i += size)
arr.push(item.slice(i, i + size));
console.log(arr);
});
the output of this is
["d","o","g"]
["d","o","g"," ","c","a","t"]
etc.
which is not what i want. Im not sure why its splitting it into each individual letter instead of each value in the array.
I am trying to avoid SPLICE by all means and only use SLICE if necessary.
Thanks in advance.
EDIT: my output for the code is now. Ive tried to use flat() but that just brings it back to ["dog", "cat"].
var animals = [
[
[
"dog"
],
[
"cat"
]
]
];
I have the dog and cat that are in nested arrays and Im trying to get rid of the extra array so it would look like this instead
var animals = [
[
"dog"
],
[
"cat"
]
];
You can use map here to take those individual values and return them to a new array as arrays, just by wrapping them in braces.
let arrays = ['cat', 'apple', 'frog'];
console.log(JSON.stringify(arrays));
let final = arrays.map(m=>{return [m]});
console.log(JSON.stringify(final));
You can also define a splitter function and just call it against the array.
let arrays= ['cat', 'apple', 'frog'];
const splitter=(arr)=>arr.map(m=>{return [m]});
console.log(JSON.stringify(splitter(arrays)));
This would be useful if you had to do it in a lot of places or if you had an array of these arrays and wanted to iterate over that and use the splitter constant on each, like this:
let arrays = [
['dog'],
['dog', 'cat'],
['cat', 'apple', 'frog'],
['apple', 'dog']
];
const splitter=(arr)=>arr.map(m=>{return [m]});
let final = arrays.map(m=>{return splitter(m)});
console.log(final);
or if you needed to do this recursively with an array of unknown depth:
let arrays = [
['dog'],
['dog', 'cat'],
[
['test', 'it', 'out'],
['cat', 'apple', 'frog']
],
[
['one', 'more'],
['two', 'more']
],
['apple', 'dog']
];
const splitter=(arr)=>arr.map(m=>{
return Array.isArray(m) ? splitter(m) : [m]
});
let final = splitter(arrays);
console.log(final);
You can use .map() for each array:
const animals = ['dog', 'cat', 'lama']
const result = animals.map(animal => [animal])
console.log(result)
// [ ['dog'], ['cat'], ['lama'] ]
You can then push the results into another array or you can use .reduce() to generate the end result.
var arrays = [
'dog',
'dog,cat',
'cat,apple,frog',
'apple,dog'
];
var arr = [];
arrays.forEach((item) => arr.push(item.split(",")));
console.log(arr);
Do you mean like this?

A way to push array of objects into an array

Here is the array of objects that is to be push to an array
[{"a":11,"b":21},{"a":31,"b":41},{"a":10,"b":20}]
How to achieve this array below from the above
"array": [
[
[
11,
21
],
[
31,
41
],
[
10,
20
],
[
11, //first object again
21
]
]
]
Used array map to push elements but couldn't figure out a way to push the first object again
var array1 = [{"a":11,"b":21},{"a":31,"b":41},{"a":10,"b":20}];
var array2 = [array1.map(item=>[item.a, item.b])];
console.log(array2);
You can do this,
var array1 = [{"a":11,"b":21},{"a":31,"b":41},{"a":10,"b":20}];
array1.push(array1[0])
var array2 = [array1.map(item=>[item.a, item.b])];
console.log(array2);
You just add another line of code that inserts that first index.
var array1 = [{"a":11,"b":21},{"a":31,"b":41},{"a":10,"b":20}];
var array2 = [array1.map(item=>[item.a, item.b])];
array2[0].push([array1[0].a, array1[0].b]);
console.log(array2);
Do you need the double array on the outside though?
Anyway, another way would be to just copy the first array you originally pushed.
var array1 = [{"a":11,"b":21},{"a":31,"b":41},{"a":10,"b":20}];
var array2 = [array1.map(item=>[item.a, item.b])];
array2[0].push(array2[0][0].slice());
console.log(array2);
And you can also make your .map() a little different using Object.values:
var array1 = [{"a":11,"b":21},{"a":31,"b":41},{"a":10,"b":20}];
var array2 = [array1.map(Object.values)];
array2[0].push(array2[0][0].slice());
console.log(array2);
This can be done my manually pushing the first element again after you've done the mapping.
The unshift() method can be used to push to the front of array.
var array2 = [array1.map(item=>[item.a, item.b])];
array2.unshift([array1[0].a, array1[0].b])
I agree with slappy's answer, but no need to apply slice
const arr = [{"a":11,"b":21},{"a":31,"b":41},{"a":10,"b":20}];
const arr2 = [arr.map(item=>[item.a, item.b])];
arr2.push(arr2[0][0]);

sort array of objects according list sequence [duplicate]

This question already has answers here:
Sort an object array by custom order
(5 answers)
Closed 4 years ago.
Hello guys I have a task on sort. Here is the deal:
I have an array
arr = [{role:'mom', name:'a'}, {role:'dad', name:'d'}, {role:'bro', name: 'c'}]
and sort sequence list sortSequence = ['dad','mom','bro']
so according this list I need an output array to be equal
arr = [{role:'dad', name:'d'}, {role:'mom', name:'a'}, {role:'bro', name: 'c'}]
How can use sort method to do this?
const sortAccordingList = (list, arr) => {
//... ?
}
You can use indexOf to get the index of the role
var sortSequence = ['dad', 'mom', 'bro'];
var arr = [{role:'mom', name:'a'}, {role:'dad', name:'d'}, {role:'bro', name: 'c'}];
arr.sort((a, b) => sortSequence.indexOf(a.role) - sortSequence.indexOf(b.role));
console.log(arr);
You can also make sortSequence as an object. This will make it easier to get the sort sequence. Like:
var sortSequence = {dad:1,mom:2,bro:3};
var arr = [{role:'mom', name:'a'}, {role:'dad', name:'d'}, {role:'bro', name: 'c'}];
arr.sort((a, b) => sortSequence[a.role] - sortSequence[b.role]);
console.log(arr);

Javascript push an array to a 2-dim array

So i have 2 single dim arrays
array1 = [1,2,3];
array2 = [4,5,6];
And an empty 2-dim array
setArray = [[],[]];
How am i going to push the contents of the arrays to setArray so that it looks like this... considering we don't know the length of the single dim arrays?
setArray = [
[1,2,3],
[4,5,6]
];
I'm working on a project and my problem looks like this. Thank you.
if you just want to push contents of the two arrays in setArray you can do something like this:
Each element of setArray will have a reference to one of the arrays.
var array1 = [1,2,3], array2 = [4,5,6];
var setArray = [];
setArray.push(array1);
setArray.push(array2);
console.log(setArray);
array1 = [1,2,3]; array2 = [4,5,6];
setArray = [array1,array2];
console.log(setArray)
You can do it this way too.

How to use array variable in array?

I have an array and I want to put same array and other array inside of the first array.
var arr=["a","b","c",arr,arr2];
var arr2=["a","b"];
var arr3=[];
arr3=arr[3];
When I print out arr, I can see
["a","b","c",,]
But if I print out arr3, The result is undefined.
How can I fix it?
You need to do this in the right order:
var arr1 = [];
var arr2 = [ "a", "b" ];
// Now arr1 and arr2 are defined so you can throw them into another array:
var arr3 = [ "a", "b", "c", arr1, arr2 ];
You've defined arr as part of itself - arr[3] is arr. But at the time, arr doesn't exist yet, so it comes out as undefined.

Categories

Resources