I work on Angular and use Typescript. I have two arrays array1 and array2 which I have parsed from an API.
A console.log on array1 looks like this :
A console.log on array2 looks like this :
I'd like to create an two dimensionnal array which would merge the two arrays one element by element (id 0 with id 0, id 1 with id 1, id 2 with id 2 and so on). To be clearer the result would be :
[["Outils sali", "saunier"], ["outils elem", "outils trad"], ["outils trad", "outils sali"], .... ];
Would you have any ideas to realize that trick ?
Any help would be very appreciated, thank you !
If both have the same length just use a map operator
array1 = []; // imagine filled
array2 = []; // imagine filled
let result = array1.map((array1Value, index) => [array1Value, array2[index]]);
You can use Array.map() to give you the desired result, returning an element from arr1 and arr2 for each iteration.
const arr1 = ['outils sali', 'outils elem', 'outils trad', 'matériel', 'produit'];
const arr2 = ['saunier','outils trad', 'outils sali', 'outils trad', 'matériel'];
const result = arr1.map((el, idx) => [el, arr2[idx]]);
console.log('Result:', result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
const arr1 = ["outils sali", "outils elem", "outils trad", "materiel", "produit"];
const arr2 = ["saunier", "outils trad", "outils sali", "outils trad", "materiel"];
const newArray = []
let subArray = []
for(let i = 0; i<arr1.length; i++) {
subArray = createArray(arr1[i],arr2[i])
newArray.push(subArray)
}
function createArray(elem1,elem2) {
return [elem1,elem2]
}
console.log(newArray)
Related
I have two arrays like:
arr1 = ["orange","banana"]
arr2 = [{"fruit"= ["pineapple","banana"]},{"fruit"= ["grapes","apple"]},{"fruit"= ["apple","orange"]}]
And i need to filter if in second array exists an item of the first.
I am trying to do this:
let kFilter = arr1.map(itemY => { return itemY; });
let filteredK = arr2.filter(itemX => kFilter.includes(itemX.fruit));
But no success :-(
First to avoid too much iteration convert the simple array to an object something like following. Otherwise the complexity will be high
const fruitMap = {
"orange": 1,
"banana": 1
};
Then you have to iterate over each of the items in second array
arr2.forEach(fruitsObj => {
let arr = fruitsObj['fruit'];
for (let i = 0; i < arr.length(); i ++) {
if (fruitMap[arr[i]]) {
arr.splice(i, 1);
}
}
})
//declaration variables correctly
let arr1 = ["orange","banana"]
let arr2 = [{"fruit" : ["pineapple","banana"]},{"fruit" : ["grapes","apple"]},{"fruit": ["apple","orange"]}];
//filter using reduce
arr2.filter((e)=>arr1.reduce((a,i)=>a||e["fruit"].includes(i),false))
//filter using some
arr2.filter((e)=>arr1.some((i)=>e["fruit"].includes(i)))
I have two arrays;selectedFunction say array1. with these values
['0x0000000000000000', '0x4046ebae00000ab003','0xd6d75f5100000cd0001']
and allFunctions say array2. with these values ;
[ '0x000fba16', '0x4046ebae', '0x517cf73e', '0xd6d75f51' ]
if element in array1 starts with the given element from array2, then push that element of array1 into myFinalSelectedFunctions[] say array3. In above arrays, 2nd and 3rd elements of array1 should be pushed into array3. How to perform such task in javascript/Nodejs ? I have basic knowledge of javascript, not an expert.
You can use .filter() with .some() to return true if a hex code from array1 .startsWith() a hex code in array2:
const array1 = ['0x0000000000000000', '0x4046ebae00000ab003','0xd6d75f5100000cd0001'];
const array2 = [ '0x000fba16', '0x4046ebae', '0x517cf73e', '0xd6d75f51' ];
const res = array1.filter(hex => array2.some(code => hex.startsWith(code)));
console.log(res);
Yo can do following:
const arr1 = ['0x0000000000000000', '0x4046ebae00000ab003','0xd6d75f5100000cd0001'];
const arr2 = [ '0x000fba16', '0x4046ebae', '0x517cf73e', '0xd6d75f51' ]
const arr3 = [];
for (let i = 0; i < arr1.length; i++) {
for (let j = 0; j < arr2.length; j++) {
if (arr1[i].startsWith(arr2[j])) {
arr3.push(arr1[i])
}
}
}
console.log(arr3)
Answer by #nick-parsons is much cleaner. You can go for it.
I have the following code
var Louis = [ 'Louis.IX', 'Louis.VIII' ]
var array1 = [];
var array2 = [];
for (var i = 0; i < Louis.length; i++) {
var split = Louis[i].split(".");
array1.push(split[0]); // before the dot
array2.push(split[1]); // after the dot
}
console.log("Louisname", array1);
console.log("Louisnum", array2);
and the output is
Louisname [ 'Louis', 'Louis' ]
Louisnum [ 'IX', 'VIII' ]
Now any idea on how can i revert the output into the initial array? Please help me, thanks.
You can use .map() with its second index argument to join elements in the first array with the second array by returning a string which contains elements in both arrays like so:
const array1 = ["Louis", "Louis"];
const array2 = ["IX","VIII"];
const original = array1.map((v, i) => `${v}.${array2[i]}`);
console.log(original);
If you're new to JS, here is a more straightforward/imperative way of achieving the same result (see code comments for details):
const array1 = ["Louis", "Louis"];
const array2 = ["IX","VIII"];
const original = [];
for(let i = 0; i < array1.length; i++) { // loop through all elements in array 1
const original_str = array1[i] + "." + array2[i]; // join array element `i` in array1 with array element `i` in array2
original.push(original_str); // add the joined string to the `original` array
}
console.log(original);
I have two array. I want to merge this two arrays into one array. One array consisting keys and another one values.My array looks like
productId = [8,7,9];//Key Element
quantity = ["5","1","3"];//Value Element
//expected new array
newarray = {
"8": 5,
"7": 1,
"9": 3
}
I already tried to merge these arrays, in this way
var newArray = {};
for(var i=0; i< productId.length; i++){
newArray[productId[i]] = quantity [i];
}
console.log(newArray);
It returns
Object [ <7 empty slots>, "5", "1", "3" ]
You are working in firefox so you may get this type of issue because the problem might be caused at how Firefox' console.log has interpreted the input object.
Please look here
Empty slots in JavaScript objects?
Try this
var productId = [8,7,9];
var quantity = ["5","1","3"];
var newarray = {};
productId.forEach((key, i) => newarray[key] = quantity[i]);
console.log(newarray);
Try the following:
var productId = [8,7,9];//Key Element
var quantity = ["5","1","3"];//Value Element
var obj = {};
var i = 0;
for(var k of productId) {
obj[k] = parseInt(quantity[i]);
i++;
}
console.log(obj);
Your new "array" is not an Array but an Object.
You can iterate on one of the arrays using Array.reduce to construct the object.
Something like that:
const arr1 = ['8', '2', '4'];
const arr2 = ['28', '12', '45'];
const result = arr1.reduce((obj, currentItem, index) => {
obj[currentItem] = arr2[index];
return obj;
}, {});
console.log(result);
I have one array like this one:
array1=[{value:1, label:'value1'},{value:2, label:'value2'}, {value:3, label:'value3'}]
I have a second array of integer :
array2=[1,3]
I would like to obtain this array without a loop for :
arrayResult = ['value1', 'value3']
Does someone know how to do it with javascript ?
Thanks in advance
Map the elements in array2 to the label property of the element in array1 with the corresponding value:
array2 // Take array2 and
.map( // map
function(n) { // each element n in it to
return array1 // the result of taking array1
.find( // and finding
function(e) { // elements
return // for which
e.value // the value property
=== // is the same as
n; // the element from array2
}
)
.label // and taking the label property of that elt
;
}
)
;
Without comments, and in ES6:
array.map(n => array1.find(e => e.value === n).label);
You can use .filter and .map, like this
var array1 = [
{value:1, label:'value1'},{value:2, label:'value2'}, {value:3, label:'value3'}
];
var array2 = [1, 3];
var arrayResult = array1.filter(function (el) {
return array2.indexOf(el.value) >= 0;
}).map(function (el) {
return el.label;
});
console.log(arrayResult);
A simple for-loop should suffice for this. In the future you should seriously post some code to show what you have tried.
var array1=[{value:1, label:'value1'},{value:2, label:'value2'}, {value:3, label:'value3'}];
var array2=[1,3];
var result = [];
for (var i = 0; i < array2.length; i++){
result.push(array1[array2[i]-1].label);
}
console.log(result); //["value1", "value3"]
JSBIN
Good answers all. If I may suggest one more alternative using Map as this seems to be suited to a key:value pair solution.
var arr1 = [ {value:1, label:'value1'}, {value:2, label:'value2'}, {value:3, label:'value3'} ];
var arr2 = [1, 3];
// create a Map of the first array making value the key.
var map = new Map( arr1.map ( a => [a.value, a.label] ) );
// map second array with the values of the matching keys
var result = arr2.map( n => map.get ( n ) );
Of course this supposes that the key:value structure of the first array will not become more complex, and could be written in the simpler form of.
var arr1 = [[1,'value1'], [2,'value2'], [3,'value3']]; // no need for names
var arr2 = [1, 3];
var map = new Map( arr1 ); // no need to arr1.map ;
var result = arr2.map( n => map.get ( n ) );
Just index the first array using the _.indexBy function:
var indexedArray1 = _.indexBy(array1, "value");
_.map(array2, function(x) { return indexedArray1[x].label; });