Convert a 2D JavaScript array to a 1D array [duplicate] - javascript

This question already has answers here:
Merge/flatten an array of arrays
(84 answers)
Closed 6 years ago.
I want to convert a 2D JavaScript array to a 1D array, so that each element of the 2D array will be concatenated into a single 1D array.
Here, I'm trying to convert arrToConvert to a 1D array.
var arrToConvert = [[0,0,1],[2,3,3],[4,4,5]];
console.log(get1DArray(arrToConvert)); //print the converted array
function get1DArray(2dArr){
//concatenate each element of the input into a 1D array, and return the output
//what would be the best way to implement this function?
}

Use the ES6 Spread Operator
arr1d = [].concat(...arr2d);
Note that this method is only works if arr2d has less than about 100 000 subarrays. If your array gets larger than that you will get a RangeError: too many function arguments.
For > ~100 000 rows
arr = [];
for (row of table) for (e of row) arr.push(e);
concat() is too slow in this case anyway.
The Underscore.js way
This will recursively flatten arrays of any depth (should also work for large arrays):
arr1d = _.flatten(arr2d);
If you only want to flatten it a single level, pass true as the 2nd argument.
A short < ES6 way
arr1d = [].concat.apply([], arr2d);

Try .concat():
var arrToConvert = [[0,0,1],[2,3,3],[4,4,5]];
var newArr = [];
for(var i = 0; i < arrToConvert.length; i++)
{
newArr = newArr.concat(arrToConvert[i]);
}
console.log(newArr);

Try .reduce()
var test2d = [
["foo", "bar"],
["baz", "biz"]
];
var merged = test2d.reduce(function(prev, next) {
return prev.concat(next);
});
console.log(merged)
Source: http://jsperf.com/2-dimensional-array-merge

How about:
var arrToConvert = [[0,0,1],[2,3,3],[4,4,5]];
function get1DArray(arr){
return arr.join().split(",");
}
console.log(get1DArray(arrToConvert));
http://jsfiddle.net/JRR4J/

var arrToConvert = [[0,0,1],[2,3,3],[4,4,5]];
var modifiedArray = arrToConvert.map(function(array){
return array[0]+array[1]+array[2];
});
Another Example
var passengers = [
["Thomas", "Meeks"],
["Gregg", "Pollack"],
["Christine", "Wong"],
["Dan", "McGaw"]
];
var modifiedNames = passengers.map(function(convArray){
return convArray[0]+" "+convArray[1];
});

var arrToConvert = [[0, 0, 1], [2, 3, 3], [4, 4, 5]];
function get1DArray(arr){
var result = new Array();
for (var x = 0; x < arr.length; x++){
for (var y = 0; y < arr[x].length; y++){
result.push(arr[x][y])
}
}
return result
}
alert (get1DArray(arrToConvert))
http://jsfiddle.net/Saturnix/ReeqQ/

Related

push more than one elements at same index in array

how to push more than one element at one index of a array in javascript?
like i have
arr1["2018-05-20","2018-05-21"];
arr2[5,4];
i want resulted 4th array to be like:
arr4[["2018-05-20",5],["2018-05-21",4]];
tried pushing like this:
arr1.push("2018-05-20","2018-05-21");
arr1.push(5,4);
and then finally as:
arr4.push(arr1);
But the result is not as expected. Please someone help.
Actually i want to use this in zingChart as :
Options Data
Create an options object, and add a values array of arrays.
Calendar Values
In each array, provide the calendar dates with corresponding number values in the following format.
options: {
values: [
['YYYY-MM-DD', val1],
['YYYY-MM-DD', val2],
...,
['YYYY-MM-DD', valN]
]
}
Your question is not correct at all, since you cannot push more than one element at the same index of an array. Your result is a multidimensional array:
[["2018-05-20",5],["2018-05-21",4]]
You have to create a multidimensional array collecting all your data (arrAll)
Then you create another multidimensional array (arrNew) re-arranging previous data
Try the following:
// Your Arrays
var arr1 = ["2018-05-20","2018-05-21"];
var arr2 = [5, 4];
//var arr3 = [100, 20];
var arrAll = [arr1, arr2];
//var arrAll = [arr1, arr2, arr3];
// New Array definition
var arrNew = new Array;
for (var j = 0; j < arr1.length; j++) {
var arrTemp = new Array
for (var i = 0; i < arrAll.length; i++) {
arrTemp[i] = arrAll[i][j];
if (i === arrAll.length - 1) {
arrNew.push(arrTemp)
}
}
}
//New Array
Logger.log(arrNew)
Assuming the you want a multidimensional array, you can put all the input variables into an array. Use reduce and forEach to group the array based on index.
let arr1 = ["2018-05-20","2018-05-21"];
let arr2 = [5,4];
let arr4 = [arr1, arr2].reduce((c, v) => {
v.forEach((o, i) => {
c[i] = c[i] || [];
c[i].push(o);
});
return c;
}, []);
console.log(arr4);

Convert every nth element of an array to an object in javascript

I'd like to convert:
var people = [1,"Shaw","Tanzania",2,"Nelson","Kazakhstan",3,"Garcia","Madagascar"]
into:
var rows = [
[1, "Shaw", "Tanzania"],
[2, "Nelson", "Kazakhstan"],
[3, "Garcia", "Madagascar"]
];
I've seen this answer to a similar question, but I don't understand how that works and extend it to every nth element
Use a for loop with Array#slice. You iterate the original array using the require chunk size as the step. On each iteration you slice the relevant part from the original array (slice doesn't mutate the array), and push it into the result array.
var people = [1,"Shaw","Tanzania",2,"Nelson","Kazakhstan",3,"Garcia","Madagascar"];
var result = [];
var chunkSize = 3;
for(var i = 0; i < people.length; i+= chunkSize) {
result.push(people.slice(i, i + chunkSize));
}
console.log(result);

Check if arrays contain shared elements regardless of index

I'd like to check if two arrays share elements regardless of order.
Given
array A: ['hello', 'how', 'are', 'you']
array B: ['how', 'are', 'hello']
Will return matches for 'hello', 'how', and 'are'
There seems to be something for PHP, array_intersect() (Check if array contains elements having elements of another array), but nothing for JavaScript.
I would use in if the values were in an object, but they are not:
if (key in obj) {
}
I could also do array.sort() to both arrays, but it's not guaranteed that both arrays will have same number of values. Therefore even if they are sorted, the compared indices would be off anyway.
How can I do this in JavaScript?
You can use filter to check if the same element is present in the other array.
var arr1 = ['hello', 'how', 'are', 'you'];
var arr2 = ['how', 'are', 'hello'];
var commonElements = arr1.filter(function(e) {
return arr2.indexOf(e) > -1;
});
console.log(commonElements);
You can also define this function on Array prototype
Array.prototype.intersection = function(arr) {
return this.filter(function(e) {
return arr.indexOf(e) > -1;
});
};
var arr1 = ['hello', 'how', 'are', 'you'],
arr2 = ['how', 'are', 'hello'];
var commonElements = arr1.intersection(arr2);
console.log(commonElements);
Considering performance I'd convert one of the array to an object, and then check intersection by traversing the other.
var arr1 = ['hello', 'how', 'are', 'you'];
var arr2 = ['how', 'are', 'hello'];
var set = {};
var intersect = [];
for (var i = 0; i < arr1.length; i++)
set[arr1[i]] = true;
for (var i = 0; i < arr2.length; i++)
if (set[arr2[i]]) intersect.push(arr2[i]);
But this method will ignore duplicate items in the arrays. And this may seem verbose compared to the filter and find solution. This may be helpful if you're doing intersection of large arrays.
In this approach, the first array is converted into a map, for fast lookup.
The second array is matched against the first.
The complexity is O(a) + O(b).
Pro: Elegance.
Con: Matching is continued after the overlap is detected.
function array_overlap(a, b) {
const lookup = a.reduce((m, n) => (m[n]=true, m), {});
const status = b.reduce((m, n) => (lookup[n] || m), false);
return status;
}
In ES6 syntax:
var intersection = arr1.filter( e => arr2.includes( e ) )

javascript remove remove values from array smaller then value

I have an array in javascript like this (1,2,3,4,5,6,7,8) and i want to remove al the values that are smaller than 5. So the array that remains is (1,2,3,4). How to do this with javascript or jquery...
You can filter the array with array.filter()
var array = [1,2,3,4,5,6,7,8];
var new_array = array.filter(function(item) {
return item < 5;
});
FIDDLE
or if you have to support IE8 and below, you can do it the old fashion way
var array = [1,2,3,4,5,6,7,8],
new_array = [];
for (var i=0; i<array.length; i++) {
if (array[i] < 5) new_array.push(array[i])
}
FIDDLE
I think you want to remove items larger than 5, but jquery grep should do it:
https://api.jquery.com/jQuery.grep/
Use .map(). This will remove values less than 5 and remaining array values will be removed from array.
var arr = $.map( [ 1,2,3,4,5,6,7,8 ], function( n ) {
return n < 5 ? n : null;
});
console.log(arr);
DEMO
or
Use .grep(). This will remove values less than 5 and remaining values will be removed from the array.
var arr = $.grep( [ 1,2,3,4,5,6,7,8 ], function( n ) {
return n < 5;
});
console.log(arr);
DEMO
I will suggest you to go with grep based on jsperf result.
http://jsperf.com/map-vs-grep/2
var orig= [1,2,3,4,5,6,7,8];
just in case they're out of order:
var copy=orig.sort();
then:
var result = copy.splice(0,copy.lastIndexOf(4)+1);
http://jsfiddle.net/LXaqe/
In this case you can use JavaScript is good in compare of jQuery. Because JavaScript *Execution* fast compare to a jQuery.
Check this Demo jsFiddle
JavaScript
var filtered = [1,2,3,4,5,6,7,8].filter(issmall);
function issmall(element) {
return element < 5 ;
}
console.log(filtered);
Result
[1, 2, 3, 4]
JavaScript filter() Method
Var arr = [1,2,3,4,5,6,7];
var newarr = [];
For(var i=0 ; i<=arr.length ; i++){
if(arr[i] < 5){
newarr.push(arr[i]);
}
}

zip two arrays Javascript [duplicate]

This question already has answers here:
How to merge two arrays in JavaScript and de-duplicate items
(89 answers)
Closed 9 years ago.
I have two arrays in javascript:
var array1 = ["a","b","c"];
var array2 = ["e","f","g"];
And I want the resulting array to be like this:
array3 = ["a","e","b","f","c","g"];
Any way to do this?
Will a straightforward loop do it?
array3 = new Array();
for(var i = 0; i < array1.length; i++)
{
array3.push(array1[i]);
array3.push(array2[i]);
}
You can try with concat() method:
var array1 = ["a","b","c"];
var array2 = ["e", "f","g"];
var array3 = array1.concat(array2); // Merges both arrays
For your specific requirement, you have to follow this:
function mergeArrays(a, b){
var ret = [];
for(var i = 0; i < a.length; i++){
ret.push(a[i]);
ret.push(b[i]);
}
return ret;
}
This should work:
function zip(source1, source2){
var result=[];
source1.forEach(function(o,i){
result.push(o);
result.push(source2[i]);
});
return result
}
Look http://jsfiddle.net/FGeXk/
It was not concatenation, so the answer changed.
Perhaps you would like to use: http://underscorejs.org/#zip

Categories

Resources