javascript find matching variables between two nested arrays - javascript

I have two nested arrays.
arr1 = [["image1","shirt", "collared",40],["image3","shirt", "buttoned",40]]
arr2 = [["image1","blue"],["image2","red"]]
The desired output is : If the image names (image) match, I want to return the color from the second array to a variable.
I have tried using two for loops:
var color = for (var i = 0; i < arr1.length; i++ ) {
for (var j = 0; j < arr2.length; j++ ) {
if (arr1[i][0] === arr2[j][0]) {
return arr2[j][1]
}
}
Since this is a larger part of a program, The first loop gets executed much before the second loop...however both are nested into each other in the order that I have specified.....I am trying to using the variable to color some html elements, but my entire program gets halted. I am not sure if my approach is right.

Feels like you're trying to use the second array as a lookup into the first. Here's a way to do this by transforming it into an object:
function toLookupTable(shirtColors) {
//keys will be image names, values will be colors
const lookupTable = {};
shirtColors.forEach(shirtColor => {
//use array destructuring
const [ image, color ] = shirtColor;
lookupTable[image] = color;
});
return lookupTable;
}
const colorLookup = toLookupTable( [["image1","blue"],["image2","red"]] );
console.log(colorLookup["image2"]); //outputs "red"

Use Array#reduce and Array#findIndex
I want to return the color from the second array to a variable.
const arr1 = [["image1","shirt", "collared",40],["image3","shirt", "buttoned",40]]
const arr2 = [["image1", "blue"],["image2","red"]]
const res = arr2.reduce((a,[image,color])=>{
if(arr1.findIndex(([n])=>n===image) > -1) a.push(color);
return a;
}, []);
console.log(res);

You can use reduce
let arr1 = [["image1","shirt", "collared",40],["image3","shirt", "buttoned",40]];
let arr2 = [["image1","blue"],["image2","red"]];
let op = arr1.reduce((out,inp,index)=>{
if(arr2[index].includes(inp[0])){
out.push(arr2[index][1])
}
return out
},[] )
console.log(op)

Related

How to get a value of column 'b' from a 2d array where column 'a' matches a single array in javascript

New to javascript. Need some guidance on the problem below:
I have these arrays:
array1 = [['a1'], ['a2'], ['a3']];
array2 = [['a1',4], ['a3',3], ['a6',2]];
How can i get the matching arrays whereby array1 first col = array2 first col?
Example expected result:
[['a1',4], ['a3',3]]
I hope the question makes sense. Not really sure how to approach this since the structure of these two arrays are different.
You can use filter to filter out the elements. Inside filter method check if elements exist in array1. You can flat array1 to check effeciently.
let flatArr1 = array1.flat(); //["a1", "a2", "a3"]
const result = array2.filter(([x,y]) => flatArr1.includes(x));
console.log(result) // for instance
This is my solution for your problem:
const compare = (array1, array2) => {
let matched = [];
const keys = [].concat(...array1);
for(let i = 0; i < array2.length; i++) {
for(let j = 0; j < array2.length; j++) {
let result = array2[i][j];
if(keys.includes(result)) {
matched.push(array2[i])
}
}
}
console.log("matched: ", matched);
};

How can I use variables to decide what to change on a DOM element?

I am writing a function to iterate over an array that will determine what gets changed in an element. I have tried a few ideas including template literals but am not achieving desired results. Any ideas how to pass desired dom changes through an array into a function?
testArray = [["background", "yellow"]];
const changeElement =(id, array)=>{
let element = getElementById(id);
for(let i = 0; i<=array.length-1; i++){
for(let j = 0; j<=array.length-1; j++){
`${element}.style.${array[i][j]} = "${array[i][j+1]}"`;
}}
}
You don't need template literals. It won't work.
Simply using rectangular brackets ([ ]) will work for you.
In JavaScript, you can access the properties of objects using the dot (.) operator or using rectangular brackets ([ ]).
For example, if you have an object as follows:
var obj = {
x: "Hii",
y: 5,
};
Now if you want to access x of obj, you can access it in 2 ways:
console.log(obj.x); // Hii
// This will also work
console.log(obj["x"]); // Hii
Similarly, for y:
console.log(obj.y); // 5
// This will also work
console.log(obj["y"]); // 5
Now, in this case, element.style is an object. If you want to access property background of element.style, you can do the following:
// This won't work for your case as the property to be modified is stored in array
element.style.background = "yellow";
// But this will work!
element.style["background"] = "yellow";
So, while iterating, you can do this:
let testArray = [["background", "yellow"]];
const changeElement =(id, array) => {
let element = document.getElementById(id);
for(let i = 0; i<=array.length-1; i++){
for(let j = 0; j<=array.length-1; j++){
element.style[array[i][j]] = array[i][j+1];
}
}
}
But I think your testArray will have this format:
let testArray = [["prop1", "value1"], ["prop2", "value2"], ... ];
If so, your code will not work and can be simplified to use just one for loop as follows:
let testArray = [["background", "yellow"], ["color", "red"]];
const changeElement =(id, array) => {
let element = document.getElementById(id);
for(let i = 0; i < array.length; i++){
element.style[array[i][0]] = array[i][1];
}
}
Hope this helps :)
1) You can use Object.fromEntries to transform testArray into
{
background: "yellow"
}
and then iterate through this object.
2) look at this
const changeElement = (id, array)=>{
const element = document.getElementById(id);
for(let i = 0; i<=array.length-1; i++){
for(let j = 0; j<=array.length-1; j++){
element.style[array[i][j]] = array[i][j+1];
}
}
}
changeElement("myId", [["background", "yellow"]]);
you can get the value from an object by parentheses
3) You shouldn't using for loop. You can write less by using Array.prototype.forEach e.g.
const changeElement = (id, array)=>{
const element = document.getElementById(id);
array.forEach(value => {
element.style[value[0]] = value[1];
});
}
changeElement("myId", [["background", "yellow"]]);
https://developer.mozilla.org/pl/docs/Web/JavaScript/Referencje/Obiekty/Array/forEach
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/fromEntries
https://developer.mozilla.org/pl/docs/Web/JavaScript/Referencje/Obiekty/Array/map

How to remove certain elements from an array into a new array and leave the others only the original array?

How to write a function to remove certain elements into a new array and leave the original array with only the remaining elements?
the first part is easy using a for loop pushing the even numbers into a new array but mutating the original array to leave only the odd numbers is hard
function remove(arr, cb){
var removed = [];
var newArr = [];
for(var i = 0; i < arr.length; i++) {
if(cb(arr[i], i, arr)) {
removed.push(arr[i]);
}
}
return removed;
}
Use an else statement to fill newArr with values that should stay in the original arr, then empty it using splice() before copying the items from newArr back into it.
function remove (arr, cb) {
var removed = [];
var newArr = [];
for (var i = 0; i < arr.length; i++) {
if (cb(arr[i], i, arr)) {
removed.push(arr[i]);
} else {
newArr.push(arr[i]);
}
}
arr.splice(0);
for (var i = 0; i < newArr.length; i++) {
arr.push(newArr[i]);
}
return removed;
}
Welcome to Stackoverflow!
Personally, I'd avoid anything that mutates an input parameter, as this increases code complexity and makes it hard to reason about what's happening from the calling side.
Instead, I'd write a method that returns an array of two arrays. This can be easily split into two variables at the calling end using by using array destructuring.
See the example below:
const splitArr = (arr, pred) =>
arr.reduce(
(prev, curr, idx) => {
prev[+pred(curr, idx, arr)].push(curr);
return prev;
}, [[], []]
);
// usage //
const myArr = [1, 2, 3, 4];
const [arr1, arr2] = splitArr(myArr, x => x > 2);
console.log(arr1);
console.log(arr2);
Because pred is a function that returns a boolean value, we can co-erce this value to 0 or 1 using +someBoolean. We can then use this value as an index to decide into which of the two output arrays the value should be pushed.
You were definitely on the right track with your solution, a couple tweaks and we can make it very readable and also very easy to work with. I tried to keep the format of what it looked like you were doing.
I do take advantage of destructuring here, this could be returned as just an object, and then reference the properties.
const myArr = [0,1,2,3,4,5,6,7,8,9,10];
const splitItems = (arr, logicFunc) => {
let secondSet = []
const firstSet = arr.filter(v => {
if (logicFunc(v)) return true
else secondSet.push(v)
})
return { firstSet, secondSet }
}
const myLogicFunc = v => (v < 3 || v == 9)
const { firstSet, secondSet } = splitItems(myArr, myLogicFunc)
console.log(`My first set: ${firstSet}`) // My first set: 0,1,2,9
console.log(`My second set: ${secondSet}`) // My second set: 3,4,5,6,7,8,10
/* OR without destructuring:
const myArrays = splitItems(myArr, myLogicFunc)
console.log(`My first set: ${myArrays.firstSet}`)
console.log(`My second set: ${myArrays.secondSet}`)
*/
Please let me know if you have any questions
In modern JavaScript apps we do not mutate arrays we create new array, this avoids side effects, so what we do is create two new arrays
const split = (source, conditionFunc) = [ source.filter(i => conditionFunc(i)), source.filter(i => !conditionFunc(i))];
Then you have an array of two arrays of the values that meed condition and those that don't and you have not caused any side effects.
const odssAndEvens = split(source, i => i % 2 === 1);
Or with reduce so you don't iterate the array twice
const split = (source, conditionFunc) = source.reduce((results, item) => {
if (conditionFunc(item)) {
results[0].push(item);
} else {
results[1].push(item);
}
return results;
}, [[],[]]);

How to create key value pair using two arrays in JavaScript?

I have two arrays, keys and commonkeys.
I want to create a key-value pair using these two arrays and the output should be like langKeys.
How to do that?
This is array one:
var keys=['en_US','es_ES', 'pt_PT','fr_FR','de_DE','ja_JP','it_IT']
This is array two:
var commonKeys=['en-*','es-*', 'pt-*','fr-*','de-*','ja-*','it-*', '*']
This is the output I need:
var langKeys = {
'en-*': 'en_US',
'es-*': 'es_ES',
'pt-*': 'pt_PT',
'fr-*': 'fr_FR',
'de-*': 'de_DE',
'ja-*': 'ja_JP',
'it-*': 'it_IT',
'*': 'en_US'
};
You can use map() function on one array and create your objects
var keys=['en_US','es_ES', 'pt_PT','fr_FR','de_DE','ja_JP','it_IT'];
var commonKeys=['en-*','es-*', 'pt-*','fr-*','de-*','ja-*','it-*', '*'];
var output = keys.map(function(obj,index){
var myobj = {};
myobj[commonKeys[index]] = obj;
return myobj;
});
console.log(output);
JavaScript is a very versatile language, so it is possible to do what you want in a number of ways. You could use a basic loop to iterate through the arrays, like this:
var keys=['en_US','es_ES', 'pt_PT','fr_FR','de_DE','ja_JP','it_IT']
var commonKeys=['en-*','es-*', 'pt-*','fr-*','de-*','ja-*','it-*', '*']
var i;
var currentKey;
var currentVal;
var result = {}
for (i = 0; i < keys.length; i++) {
currentKey = commonKeys[i];
currentVal = keys[i];
result[currentKey] = currentVal;
}
This example will work in all browsers.
ES6 update:
let commonKeys = ['en-*', 'es-*', 'pt-*', 'fr-*', 'de-*', 'ja-*', 'it-*', '*'];
let keys = ['en_US', 'es_ES', 'pt_PT', 'fr_FR', 'de_DE', 'ja_JP', 'it_IT', 'en_US'];
let zipArrays = (keysArray, valuesArray) => Object.fromEntries(keysArray.map((value, index) => [value, valuesArray[index]]));
let langKeys = zipArrays(commonKeys, keys);
console.log(langKeys);
// let langKeys = Object.fromEntries(commonKeys.map((val, ind) => [val, keys[ind]]));
What you want to achieve is to create an object from two arrays. The first array contains the values and the second array contains the properties names of the object.
As in javascript you can create new properties with variales, e.g.
objectName[expression] = value; // x = "age"; person[x] = 18,
you can simply do this:
var keys=['en_US','es_ES', 'pt_PT','fr_FR','de_DE','ja_JP','it_IT'];
var commonKeys=['en-*','es-*', 'pt-*','fr-*','de-*','ja-*','it-*', '*'];
var langKeys = {};
var i;
for (i=0; i < keys.length; i++) {
langKeys[commonKeys[i]] = keys[i];
}
EDIT
This will work only if both arrays have the same size (actually if keys is smaller or same size than commonKeys).
For the last element of langKeys in your example, you will have to add it manually after the loop.
What you wanted to achieve was maybe something more complicated, but then there is missing information in your question.
Try this may be it helps.
var langKeys = {};
var keys=['en_US','es_ES', 'pt_PT','fr_FR','de_DE','ja_JP','it_IT']
var commonKeys=['en-*','es-*', 'pt-*','fr-*','de-*','ja-*','it-*', '*']
function createArray(element, index, array) {
langKeys[element]= keys[index];
if(!keys[index]){
langKeys[element]= keys[index-(commonKeys.length-1)];
}
}
commonKeys.forEach(createArray);
console.info(langKeys);
Use a for loop to iterate through both of the arrays, and assign one to the other using array[i] where i is a variable representing the index position of the value.
var keys = ['en_US', 'es_ES', 'pt_PT', 'fr_FR', 'de_DE', 'ja_JP', 'it_IT'];
var commonKeys = ['en-*', 'es-*', 'pt-*', 'fr-*', 'de-*', 'ja-*', 'it-*', '*'];
var langKeys = {};
for (var i = 0; i < keys.length; i++) {
var commonkey = commonKeys[i];
langKeys[commonkey] = keys[i];
}
console.log(JSON.stringify(langKeys));
let keys = ['en_US', 'es_ES', 'pt_PT', 'fr_FR', 'de_DE', 'ja_JP', 'it_IT'];
let commonKeys = ['en-*', 'es-*', 'pt-*', 'fr-*', 'de-*', 'ja-*', 'it-*', '*'];
// declaration of empty object where we'll store the key:value
let result = {};
// iteration over first array to pick up the index number
for (let i in keys) {
// for educational purposes, showing the number stored in i (index)
console.log(`index number: ${i}`);
// filling the object with every element indicated by the index
// objects works in the basis of key:value so first position of the index(i)
// will be filled with the first position of the first array (keys) and the second array (commonKeys) and so on.
result[keys[i]] = commonKeys[i];
// keep in mind that for in will iterate through the whole array length
}
console.log(result);

splitting array elements in javascript split function

Hi i have the below array element
var array =["a.READ","b.CREATE"]
I'm trying to split the elements based on "." using javascript split method
below is my code
var array1=new Array();
var array2 = new Array();
for (var i = 0; i < array .length; i++) {
array1.push(array [i].split("."));
}
console.log("this is the array1 finish ----"+array1)
The out put that i'm receiving is
[["a","READ"],["b","CREATE"]]
The expected output that i want is
array1 =["a","b"]
array2=["READ","CREATE"]
I'm stuck here any solution regarding this is much helpful
You need to add to array2 and use both elements from the returned array that String.prototype.split returns - i.e. 0 is the left hand side and 1 is the right hand side of the dot.
var array = ["a.READ", "b.CREATE"]
var array1 = []; // better to define using [] instead of new Array();
var array2 = [];
for (var i = 0; i < array.length; i++) {
var split = array[i].split("."); // just split once
array1.push(split[0]); // before the dot
array2.push(split[1]); // after the dot
}
console.log("array1", array1);
console.log("array2", array2);
We'll start off with a generic transpose function for two-dimensional arrays:
function transpose(arr1) { // to transpose a 2d array
return arr1[0].map( // take the first sub-array and map
function(_, i) { // each element into
return arr1.map( // an array which maps
function(col) { // each subarray into
return col[i]; // the corresponding elt value
}
);
}
);
}
Now the solution is just
transpose( // transpose the two-dimensional array
array.map( // created by taking the array and mapping
function(e) { // each element "a.READ" into
return e.split('.'); // an array created by splitting it on '.'
}
)
)
You are adding nothing to array2. Please use indexes properly , like below:
var array1=new Array();
var array2 = new Array();
for (var i = 0; i < array .length; i++) {
array1.push(array [i].split(".")[0]);
array2.push(array [i].split(".")[1]);
}
you can do something like this
var array =["a.READ","b.CREATE"];
var arr1= [], arr2= [];
array.forEach(function(item,index,arr){
item.split('.').forEach(function(item,index,arr){
if(index % 2 === 0){
arr1.push(item);
}else{
arr2.push(item);
}
});
});
console.log(arr1);
console.log(arr2);
DEMO
I guess this is a bit redundant but, the split method actually returns and array. Although your code was off you were not modifying array2. Consider the following.
var array = [ "a.READ" , "b.CREATE" ]
, array1 = []
, array2 = []
// cache array length
, len = array.length;
for ( var i = 0; i < len; i++ ) {
// the split method returns a new array
// so we will cache the array
// push element 0 to array1
// push element 1 to array2
var newArr = array[ i ].split('.');
array1.push( newArr[ 0 ] );
array2.push( newArr[ 1 ] );
}
console.log( 'array1: ', array1 );
console.log( 'array2: ', array2 );
Use this:
for (var i = 0; i < array .length; i++) {
var parts = array[i].split('.');
array1.push(parts[0]);
array2.push(parts[1]);
}
You have not assigned any value to Array2. You can do as shown below.
var array1=[];
var array2 = [];
for (var i = 0; i < array .length; i++) {
var arrayTemp=[];
arrayTemp.push(array [i].split("."));
array1.push(arrayTemp[0]);
array2.push(arrayTemp[1]);
}

Categories

Resources