Pick the other element in a Javascript array containing two - javascript

I have a javascript array like:
var arr = ['black', 'white'];
Now if I have a variable containing one of the element, how can I easily get the other? For example
var color = 'black';
var otherColor = '???'; // should be 'white', how can I get it?
I'm looking for the simplest/cleaner way possible.
Also, I don't want to mutate the original array.
Thanks
ANSWER
What about:
var otherColor = arr[1 - arr.indexOf(color)]

You can use Array.prototype.filter for that:
var arr = ['black', 'white'];
var color = 'black';
var otherColor = arr.filter(function(item){ return item !== color })[0];

Ternary if statement:
var otherColor = arr[0] === color ? arr[1] : arr[0];

arr.filter(x => x !== color)[0]

Here's an ES6 solution using destructuring to throw into the mix.
const arr = ['black', 'white']; // our list of values.
const [black, white] = arr; // destructured into variables black and white
const color = 'black';
cont otherColor === black ? black : white;

var otherColor = arr[1 - arr.indexOf(color)]

Related

javascript find matching variables between two nested arrays

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)

How to search item using key in object and update that value into the array?

var replaceArr = ['A','J','Q',10,2];
var originalArr = [{A:0},{2:1},{3:2},{4:3},{5:4},{6:5},{10:9},{J:10},{Q:11},{K:12}];
As per the snippet I have two array:
replaceArr and originalArr
I want to compare the replaceArr with the originalArr and get the key value from there and replace into the replaceArr.
Means after replacing the replaceArr would be == [0,10,11,9,1]
In Advanced Thanks..
you can simple use map and find from array prototype
var replaceArr = ["A", "J","Q",10,2]
var originalArr = [{A:0},{2:1},{3:2},{4:3},{5:4},{6:5},{10:9},{J:10},{Q:11},{K:12}];
replaceArr = replaceArr.map(v => originalArr.find(obj => obj[v] !== undefined)[v]);
console.log(replaceArr);
You can club all the different objects in originalArr and then search for replaceArr values in it like below
var replaceArr = ['A','J','Q',10,2]
var originalArr = [{A:0},{2:1},{3:2},{4:3},{5:4},{6:5},{10:9},{J:10},{Q:11},{K:12}]
let arrWithOneObject = Object.assign(...originalArr)
let result = replaceArr.map(d => arrWithOneObject[d])
console.log(result)
You can use javascript array foreach function
originalArr.forEach((val) => {
var replaceIndex = replaceArr.indexOf(Object.keys(val)[0]);
if (replaceIndex >= 0) {
replaceArr[replaceIndex] = val[Object.keys(val)[0]];
}
});
var replaceArr = ['A','J','Q','10','2']
var originalArr = [{A:0},{2:1},{3:2},{4:3},{5:4},{6:5},{10:9},{J:10},{Q:11},{K:12}]
originalArr.forEach((item)=>{
let property = Object.keys(item)[0];
let indexOfproperty = replaceArr.indexOf(property);
if(indexOfproperty !== -1){
replaceArr[indexOfproperty] = item[property]
}
})
console.log(replaceArr)

how can I use includes() function on nested arrays?

I have an array like this:
var arr = [];
arr = [['red', 685], ['green', 210], ['blue', 65]];
Also I have two variables:
var color = 'blue';
var number = 21;
All I'm trying to do is checking the first item of each nested array of arr and then either update the second item of it or make a new array for it.
Here is some examples:
Input:
var color = 'blue';
var number = 21;
Expected output:
arr = [['red', 685], ['green', 210], ['blue', 21]];
Input:
var color = 'yellow';
var number = 245;
Expected output:
arr = [['red', 685], ['green', 210], ['blue', 21], ['yellow', 245]];
Here is what I've tried so far:
if ( !arr.includes(color) ) {
arr.push([color, number]);
} else {
arr[color] = time;
}
But !arr.includes(color) condition is wrong. Because each item of arr is also an array. Anyway, how can I use includes() function on the first item of nested arrays?
You cannot directly use includes on nested array, however, you can use find on array.
arr.find(el => el[0] === color)
This will return the element of array found else undefined. The returned value can be used to update the second element in the array.
var arr = [
['red', 685],
['green', 210],
['blue', 65]
];
var color = 'blue';
var number = 21;
function upsert(array, color, number) {
var exists = arr.find(el => el[0] === color);
if (exists) {
exists[1] = number;
} else {
arr.push([color, number]);
}
}
upsert(arr, color, number);
console.log(arr);
var color = 'yellow';
var number = 245;
upsert(arr, color, number);
console.log(arr);
Simply iterate the array and update the value if found, else push a new value
Demo
var arr = [['red', 685], ['green', 210], ['blue', 65]];
console.log(updateArray(arr, 'blue', 21));
function updateArray(arr, color, value)
{
var isFound = false;
arr = arr.map( function(item){
if( item[0] == color )
{
isFound = true;
item[1] = value;
}
return item;
});
if ( !isFound )
{
arr.push([color, value]);
}
return arr;
}
You should make a loop that cycles through the array because, as you pointed out yourself, each element of the array is itself an array.
If you do:
for(let i = 0; i < arr.length; i++){
if ( !arr[i].includes(color) ) {
arr.push([color, number]);
} else {
arr[i][1] = time;
}
}
This way you are checking if the array at position i has the color, if it doesn't you push a new array into the array, otherwise you change the array value at index 1 of the array i

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

Get random array element where value not equal

I have an array:
arr = ["blue", "red", "green"];
How can I get a random element from the array except the element with value "red"?
I know I an use the following to get a random array element but how do I put a "where/if" statement?
The code that is guaranteed to complete would look like this:
var arr = ["blue", "red", "green"];
var onlyValidValues = arr.filter(v => v !== 'red');
if (onlyValidValues.length === 0) {
throw new Error('empty array');
}
var randomItem = onlyValidValues[Math.floor(Math.random() * onlyValidValues.length)];
So compared to other suggestions it only picks random values from an array cleaned from the "forbidden" elements.
Use Math.random() within a while loop
var arr = ["blue", "red", "green"],
val = 'red';
while (val == 'red')
val = arr[Math.floor(Math.random() * arr.length)]
console.log(val);
Or copy the array and remove red from it, then get an element
var arr = ["blue", "red", "green"],
arrNew = arr.slice(0); // copy the array
arrNew.splice(arr.indexOf('red'), 1); // remove red from it
val = arrNew[Math.floor(Math.random() * arrNew.length)] //get random element
console.log(val);
In case there is multiple red elements in array, then use filter() as in #zerkms answer.
You could do something like this:
arr = ["blue", "red", "green"];
getRandomChoice = function(arr) {
var choice = arr[Math.floor(Math.random()*arr.length)];
while (choice === "red") {
choice = arr[Math.floor(Math.random()*arr.length)];
}
return choice;
}
getRandomChoice(arr)
This may be useful..
var arr = ["blue", "red", "green"];
var item = arr[Math.floor(Math.random()*arr.length)];
while(item == "red"){
item = arr[Math.floor(Math.random()*arr.length)];
}
document.write(item)
Hope it helps to solve your problem
I've done a function using new ES6 features.
With my function you can exclude more than one element.
Here's my approach :
const arr = ["blue", "red", "green"];
function getRandomElementExcluding (...excluded){
try {
let random = Math.ceil(Math.random() * arr.length - 1);
if(excluded === undefined)
return arr[random];
else if (excluded.includes(arr[random]))
return getRandomElementExcluding(...excluded);
else
return arr[random];
} catch (e){
return false;
}
}
console.log( getRandomElementExcluding('red') );
// console.log( getRandomElementExcluding('red', 'green', 'blue') ); It will return false;

Categories

Resources