creating a new arrays from a existing array of arrays - javascript

How can I create a new array without doing for each? The new array should be as follows
labels : ["Direct", "Organic Search", "Referral"]
any suggestion using javascript?

Ok. Don't want Array.forEach()? Try using Array.map function with ES6 arrow function expression for such case:
// supposing arr is your initial array
var labels = arr.map((v) => v[0]);
console.log(labels); // ["Direct", "Organic Search", "Referral"]

It's not possible to do this without any kind of loop, but as you're suggesting, a manual iteration like a foreach isn't what you're looking for, indeed.
Array.prototype.map() is the function you need in this case. ("under the hood", it's still a loop)
Here's how you can use map to get your desired result:
var myArray = [["a", 1, 2], ["b", 3, 4], ["c", 5, 6]];
var result = myArray.map(function(current){ // For each item in `myArray`
return current[0]; // return it's first element.
}); // And use that in `result`.
console.log(result)
Note that myArray.map does not change the value of myArray. You'll need to store the returned value from .map somewhere.
If you don't need to worry about supporting anything but the latest browsers, you can make this slightly shorter, using ES6:
var myArray = [["a", 1, 2], ["b", 3, 4], ["c", 5, 6]];
var result = myArray.map((c) => c[0]);
console.log(result)

You can try following
var arr1 = []; // your main array
var labels = arr1.map(function(item){
return item[0];
});
For reference, map

Related

Google Apps Script To Combine Arrays as Columns Instead of Rows

Background
In Google Apps Script I would like to make a new array that combines two arrays vertically as columns, not as additional rows. I understand it's pretty easy to add additional rows using .concat or .push but this extends the array vertically.
Here's the code:
var ar1 = [[1,3,5],
[2,4,6]];
var ar2 = [[7,9,11],
[8,10,12]];
Desired Outcome
When running ar3 I would like the desired output to be:
[[1,3,5,7,9,11]
[2,4,6,8,10,12]]
Things I've Tried
I think this could be run as a function through concat. I have tried something like the below to no avail:
var ar3 = ar2.forEach(function (row){ ar1.concat([row[0],row[1],row[2]]); });
Could this be made even simpler with .map and return? (I know the below is very wrong, but just an example.)
var ar3 = ar1.map(function (row){ return ar1[row].concat(ar2[row]); });
Use map's index like this:
var ar1 = [[1,3,5],
[2,4,6]];
var ar2 = [[7,9,11],
[8,10,12]];
const out = ar1.map((row,i) => row.concat(ar2[i]))
console.info(out)
You can do it like this, without using concat:
var ar1 = [
[1, 3, 5],
[2, 4, 6]
];
var ar2 = [
[7, 9, 11],
[8, 10, 12]
];
const result = ar1.map((x, i) => [...x, ...ar2[i]]);
console.log('result', result)

Merge multiple arrays together if not null

I am building a React App and am using Async Actions to make request to outside API's and bring in data into my app. I have 4 arrays that I need to merge together. Since I am using Async Actions the default values if theres no data is null. I want to check to see if the array is not null and if it has a value then merge it with the others into a single array. Once I have all the data into a single array I am going to use the includes method to see if any of the values are present in the array. Using the spread operator I don't think is going to work here as it will fail as null is not an iterable. Is there a way to do this with reduce to check through each of the 4 separate arrays make sure the value is not null and then combine them together into one array.
Your question leads you to the answer. :)
Essentially you are asking how to filter all non-array inputs and then combine (or concatenate) them together into a new array.
A couple of notes on the following approach:
For better stability in filtering, rather than using a blacklist (not null), use a whitelist (Array.isArray) to ensure only arrays are combined.
The spread operator can be used to then create an arguments list for a new array's concat method.
const arr1 = [1,2];
const arr2 = null;
const arr3 = [3,4];
const arr4 = [5];
const concat = (...arrays) => [].concat(...arrays.filter(Array.isArray));
console.log(concat(arr1, arr2, arr3, arr4));
For a bit of fun, if the combined array needs to be unique values (assuming simple types for values) then including a quick cast to a Set and back to an Array can make that happen:
const arr1 = [1,2];
const arr2 = null;
const arr3 = [3,4];
const arr4 = [4,5];
const concat = (...arrays) =>[].concat(...arrays.filter(Array.isArray));
const unique = (array) => [...new Set(array)];
const concated = concat(arr1, arr2, arr3, arr4);
const uniqued = unique(concated);
console.log({concated, uniqued});
Here is a one line solution (ES6).
At the first part, we merge all arrays, and then filter array elements - we include only "not null" values and exclude duplicates:
const arr1 = [1, null, 6, 'q'],
arr2 = null,
arr3 = [1, 1, null, 1],
arr4 = ['e', 'q', 6, 1, null];
const final = []
.concat(arr1, arr2, arr3, arr4)
.filter((item, i, arr) => item && arr.indexOf(item) === i);
console.log(final); // Expected output: [1, 6, "q", "e"]
var a = [1, 2, 3]
var b = null
var c = [...a||[], ...b||[]]
console.log(c)
If you assign your arrays to properties of an object obj, you can simply iterate over the object :
const a = ["a", "1"], b = null, c = ["c", 78], d = []
const obj = { a, b, c, d }
let res = []
for(let key in obj) {
res = res.concat(Array.isArray(obj[key]) ? obj[key] : []);
}
console.log(res)

Union which mutate array in lodash

Is there a function in lodash which makes a union of two arrays by modifying the first one? Union should add the element only if there are no duplicates.
Something along the lines of
a=[1,2,3,4,5,6]; _.mergeArrays(a, [6,7]);
[1,2,3,4,5,6,7]
This can be easily done with "vanilla" JavaScript. It requires ES5 (2009) only, which is implemented by all the major web browsers.
var array = [1,2,3,4,5];
var anotherArray = [6,7];
anotherArray.forEach(function(val) {
if (array.indexOf(val) === -1) {
array.push(val);
}
});
You can use spread element, Set which does not allow duplicate entries
var a = [1, 2, 3, 4, 5];
var add = [6, 7, 3, 5];
a = [...new Set([...a, ...add])];
console.log(a);

Javascript/d3 Function for creating new array from an array of arrays

Right now I have an array of the form [[1, 2], [3, 4], ...] and need to use an array of the keys [1, 3, ...] and was wondering if there was a javascript or d3 library function that took in the array of arrays and a function, then returned a new array according to the function. Something like this:
var data = [[1, 2], [3, 4]]
var keyArray = d3.transformArray(data, function(d) { return d[0]});
// keyArray = [1, 3]
So I can avoid looping over the data array again
var keyArray = [];
for (i = 0; i < data.length; i += 1) {
keyArray.push(data[i][0]);
}
// keyArray[1, 3]
This seems like a common enough thing to do using d3, but I wasn't sure if there's a specific name for this process of using a specific object and a function to create a new object of the same type.
you can use Array.prototype.map
x = [1,2,3].map(function(item){return item+1;});
this will result int [2,3,4]
read about this here https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/map

JavaScript create use backup array

Just look at the code and you'll understand what I mean:
​var aBackup = [3, 4]; // backup array
​​var a = aBackup; // array to work with is set to backup array
a[0]--; // working with array..
a = aBackup; // array o work with will be rested
console.log(a); // returns [2, 4] but should return [3, 4]
console.log(aBackup);​ // returns [2, 4] too​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​ but should return [3, 4] too
You need to make real copies of your Arrays instead of just using a reference:
var aBackup = [3, 4]; // backup array
var a = aBackup.slice(0); // "clones" the current state of aBackup into a
a[0]--; // working with array..
a = aBackup.slice(0); // "clones" the current state of aBackup into a
console.log(a); // returns [3, 4]
console.log(aBackup); // returns [3, 4]
See MDN for documentation on the slice-method
Doesn't javascript uses pointer for arrays ? Should ​​var a = aBackup; do a copy ? otherwise the results seems normal to me...
An array is a reference type of object, so changes made to it will change the underlying value it points to, a and aBackup will point to the same value, and a change made to a will change aBackup aswell.
It is because when you do this, you are not making a copy of the array, but infact a reference to the original array.
var a IS aBackup; // if you will
When you need to do is clone the backup array.

Categories