Splitting array into multiple arrays - javascript

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?

Related

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]);

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

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)

Merge two arrays by grouping based on elements of 1st array in Javascript

I have two arrays (arr1 & arr2) like this
var arr1 = ["A","B","C"];
var arr2 = [["A","aa"], ["A","ab"], ["A","ac"],["B","ba"],["B","bb"],["B","bc"],["C","ca"],["C","cb"]];
I want to group them together into 3rd array in javascript based on the values of first array. Desired Output:
arr3 = [ ["A",["aa","ab","ac"]], ["B",["ba","bb","bc"] ], ["C",["ca","cb"]] ]
NOTE: I had arr2 to begin with and was able to retrieve first value and remove duplicates into arr1.
Please advise.
Try like this
var arr1 = ["A", "B", "C"];
var arr2 = [
["A", "aa"],
["A", "ab"],
["A", "ac"],
["B", "ba"],
["B", "bb"],
["B", "bc"],
["C", "ca"],
["C", "cb"]
];
var newVal = arr1.map(function(x) {
var filter = arr2.filter(function(y) {
return y[0] == x;
}).map(function(y) {
return y[1];
});
return [x, filter];
})
console.log(newVal);
DEMO
NOTE: I had arr2 to begin with and was able to retrieve first value and remove duplicates into arr1.
Rather than creating arr1 as a middle step, I would probably create an object as the middle step:
var obj = arr2.reduce(function(a,b){
if (!a[b[0]]) a[b[0]] = [];
a[b[0]].push(b[1]);
return a;
},{});
// obj is now {"A":["aa","ab","ac"],"B":["ba","bb","bc"],"C":["ca","cb"]}
To convert that object to your desired output array:
var arr3 = Object.keys(obj).map(function(v) { return [v, obj[v]]; });
// [["A",["aa","ab","ac"]],["B",["ba","bb","bc"]],["C",["ca","cb"]]]
If you actually need the arr1 array for something else then:
var arr1 = Object.keys(obj);
// ["A", "B", "C"]
But notice that obj is quite useful for further processing, because if you need to get the values associated with "B" you don't need to search through an array again, you can simply say obj["B"] (which will give the array ["ba","bb","bc"]). So the second "B" value is obj["B"][1].
Further reading:
.reduce()
.map()
Object.keys()

How to get first N number of elements from an array

I am working with Javascript(ES6) /FaceBook react and trying to get the first 3 elements of an array that varies in size. I would like do the equivalent of Linq take(n).
In my Jsx file I have the following:
var items = list.map(i => {
return (
<myview item={i} key={i.id} />
);
});
Then to get the first 3 items I tried
var map = new Map(list);
map.size = 3;
var items = map(i => {
return (<SpotlightLandingGlobalInboxItem item={i} key={i.id} />);
});
This didn't work as map doesn't have a set function. What can I try next?
To get the first n elements of an array, use
const slicedArray = array.slice(0, n);
I believe what you're looking for is:
// ...inside the render() function
var size = 3;
var items = list.slice(0, size).map(i => {
return <myview item={i} key={i.id} />
});
return (
<div>
{items}
</div>
)
arr.length = n
This might be surprising but length property of an array is not only used to get number of array elements but it's also writable and can be used to set array's length MDN link. This will mutate the array.
If you don't care about immutability or don't want to allocate memory i.e. for a game this will be the fastest way.
to empty an array
arr.length = 0
Use Slice Method
The javascript slice() method returns a portion of an array into a new array object selected from start to end where start and end represent the index of items in that array. The original array will not be modified.
syntax : slice(start, end)
Let us say we have an array with 7 items [5,10,15,20,25,30,35] and we want the first 5 elements from that array:
let array = [5,10,15,20,25,30,35]
let newArray = array.slice(0,5)
console.log(newArray)
You can filter using index of array.
var months = ['Jan', 'March', 'April', 'June'];
months = months.filter((month,idx) => idx < 2)
console.log(months);
Do not try doing that using a map function. Map function should be used to map values from one thing to other. When the number of input and output match.
In this case use filter function which is also available on the array. Filter function is used when you want to selectively take values maching certain criteria. Then you can write your code like
var items = list
.filter((i, index) => (index < 3))
.map((i, index) => {
return (
<myview item={i} key={i.id} />
);
});
Just try this to get first n elements from list:
const slicedList = list.slice(0, n);
Example:
const list = [1,2,3,4,5]
console.log(list.slice(0, 3)) // Should return [1,2,3]
console.log(list.slice(0, 10)) // Returns [1,2,3,4,5] since this is all we have in 1st 10 elements
The following worked for me.
array.slice( where_to_start_deleting, array.length )
Here is an example
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.slice(2, fruits.length);
//Banana,Orange ->These first two we get as resultant
Using a simple example:
var letters = ["a", "b", "c", "d"];
var letters_02 = letters.slice(0, 2);
console.log(letters_02)
Output: ["a", "b"]
var letters_12 = letters.slice(1, 2);
console.log(letters_12)
Output: ["b"]
Note: slice provides only a shallow copy and DOES NOT modify the original array.
With lodash, take function, you can achieve this by following:
_.take([1, 2, 3]);
// => [1]
_.take([1, 2, 3], 2);
// => [1, 2]
_.take([1, 2, 3], 5);
// => [1, 2, 3]
_.take([1, 2, 3], 0);
// => []
[1,2,3,4,5,6,7,8,8].slice(0, 3) = While return the first 3 elements.
Answer: [1,2,3]
How it works:
The slice() method returns a shallow copy of a portion of an array into a new array object selected from start to end (end not included) where start and end represent the index of items in that array. The original array will not be modified.
The slice() method returns a shallow copy of a portion of an array into a new array object selected from start to end (end not included) where start and end represent the index of items in that array. The original array will not be modified.
const animals = ['ant', 'bison', 'camel', 'duck', 'elephant'];
console.log(animals.slice(2));
// expected output: Array ["camel", "duck", "elephant"]
console.log(animals.slice(2, 4));
// expected output: Array ["camel", "duck"]
console.log(animals.slice(1, 5));
// expected output: Array ["bison", "camel", "duck", "elephant"]
console.log(animals.slice(-2));
// expected output: Array ["duck", "elephant"]
console.log(animals.slice(2, -1));
// expected output: Array ["camel", "duck"]
know more
With LInQer you can do:
Enumerable.from(list).take(3).toArray();
Maybe I'm missing something, but feels like kicking in an open door by suggesting to use splice()? Of course, it's important to remember that this modifies the array.
const myArray = [
'one', 'two', 'three', 'four', 'five', 'six', 'seven',
]
myArray.splice(3)
console.log(myArray)
// expected output: ['one', 'two', 'three']
It's also possible to grab the elements of the array that are outside of what is being kept:
const myArray = [
'one', 'two', 'three', 'four', 'five', 'six', 'seven',
]
const afterFirstThree = myArray.splice(3)
console.log(myArray)
// expected output: ['one', 'two', 'three']
console.log(afterFirstThree)
// expected output: ['four', 'five', 'six', 'seven']
// if n is larger than myArray.length the entire array is kept and if trying to grab the return, it will be an empty array

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