Convert every nth element of an array to an object in javascript - 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);

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

How to display the array?

I have 3 arrays:
Array1 and Array2 have connections to each other:
var Array1 = ['Bob','James','Kanye','West'];
var Array2 = [0,1,2,3];
var Array3 = [1,3,0,2];
How do I display it to this?
Array4 = ['James', 'West', 'Bob','Kanye'];
you will require 2 loops, 1 will go through each element of Array3 and Second loop will be used to find the index value will be compared with Array2 to find index of Array 1 and then that index value will be saved in Array4 from Array1
for (var i = 0; i < Array3.length; i++)
{
var index = Array3[i];
var position=-1;
for(var j=0; j < Array2.length;j++)
{
if(index==Array2[j])
{
position = j;
break;
}
}
Array4[i] = Array1[j];
}
You need to run a loop over Array, take the integer inside as indexnumber, then you print out the first array with the numbers you just took from the first array.
You need to use -- and read the documentation for -- arrays' map method:
const names = ['Bob','James','Kanye','West'];
const order = [1,3,0,2];
const orderedNames = order.map(x => names[x]);
console.log(orderedNames);
// => ["James", "West", "Bob", "Kanye"]
Fiddle: https://jsfiddle.net/68hrrjx3/
Also kinda relevant in the context of the other answers: What is the difference between declarative and imperative programming

Javascript - nested loops and indexes

I am trying to build an array that should look like this :
[
[{"name":"Mercury","index":0}],
[{"name":"Mercury","index":1},{"name":"Venus","index":1}],
[{"name":"Mercury","index":2},{"name":"Venus","index":2},{"name":"Earth","index":2}],
...
]
Each element is the concatenation of the previous and a new object, and all the indexes get updated to the latest value (e.g. Mercury's index is 0, then 1, etc.).
I have tried to build this array using the following code :
var b = [];
var buffer = [];
var names = ["Mercury","Venus","Earth"]
for (k=0;k<3;k++){
// This array is necessary because with real data there are multiple elements for each k
var a = [{"name":names[k],"index":0}];
buffer = buffer.concat(a);
// This is where the index of all the elements currently in the
// buffer (should) get(s) updated to the current k
for (n=0;n<buffer.length;n++){
buffer[n].index = k;
}
// Add the buffer to the final array
b.push(buffer);
}
console.log(b);
The final array (b) printed out to the console has the right number of objects in each element, but all the indexes everywhere are equal to the last value of k (2).
I don't understand why this is happening, and don't know how to fix it.
This is happening because every object in the inner array is actually the exact same object as the one stored in the previous outer array's entries - you're only storing references to the object, not copies. When you update the index in the object you're updating it everywhere.
To resolve this, you need to create new objects in each inner iteration, or use an object copying function such as ES6's Object.assign, jQuery's $.extend or Underscore's _.clone.
Here's a version that uses the first approach, and also uses two nested .map calls to produce both the inner (variable length) arrays and the outer array:
var names = ["Mercury","Venus","Earth"];
var b = names.map(function(_, index, a) {
return a.slice(0, index + 1).map(function(name) {
return {name: name, index: index};
});
});
or in ES6:
var names = ["Mercury","Venus","Earth"];
var b = names.map((_, index, a) => a.slice(0, index + 1).map(name => ({name, index})));
Try this:
var names = ["Mercury","Venus","Earth"];
var result = [];
for (var i=0; i<names.length; i++){
var _temp = [];
for(var j=0; j<=i; j++){
_temp.push({
name: names[j],
index:i
});
}
result.push(_temp);
}
console.log(result)
try this simple script:
var b = [];
var names = ["Mercury","Venus","Earth"];
for(var pos = 0; pos < names.length; pos++) {
var current = [];
for(var x = 0; x < pos+1; x++) {
current.push({"name": names[x], "index": pos});
}
b.push(current);
}

Fill empty array

I need to iterate from 0 to 30, but I want to do this with help of forEach:
new Array(30).forEach(console.log.bind(console);
Of course this does not work, therefor I do:
new Array(30).join(',').split(',').forEach(console.log.bind(console));
Is there other ways to fill empty arrays?
Actually, there's a simple way to create a [0..N) (i.e., not including N) range:
var range0toN = Object.keys(Array.apply(0,Array(N)));
Apparently Object.keys part can be dropped if you only want to get a proper array of N elements.
Still, like others said, in this particular case it's probably better to use for loop instead.
if you want all of item have same value, do this
var arrLength = 4
var arrVal = 0
var newArr = [...new Array(arrLength)].map(x => arrVal);
// result will be [0, 0, 0, 0]
You could try using a for loop. new Array is not a best practise
var index, // we use that in the for loop
counter, // number of elements in array
myArray; // the array you want to fill
counter = 30;
myArray = [];
for (index = 0; index < counter; index += 1) {
myArray[index] = [];
/*
// alternative:
myArray.push([]);
// one-liner
for (index = 0; index < counter; index += 1) myArray.push([]);
*/
}
If you simply want to iterate, then use for loop like this
for (var i = 0; i < 30; i += 1) {
...
...
}
Actually, if you are looking for a way to create a range of numbers, then you can do
console.log(Array.apply(null, {length: 30}).map(Number.call, Number));
It will create numbers from 0 to 29. Source : Creating range in JavaScript - strange syntax
If you insist foreach
var data = [1, 2, 3];
data.forEach(function(x) {
console.log(x);
});

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

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/

Categories

Resources