Accessing multidimensional array with an array - javascript

If the following is my array of question, how can I get the value in the position [0][2][1] by supplying the index values in an array eg:answer = [0, 2, 1].
var question = [
[
['x', 'x', 'x'],
['x', 'x', 'x'],
['x', 'x', 'x']
],
[
['x', 'x', 'x'],
['x', 'x', 'x'],
['x', 'x', 'x']
],
[
['x', 'x', 'x'],
['x', 'x', 'x'],
['x', 'x', 'x']
]
];
var answer = [0,2,1];
question.get(answer); // Is there a way like this?
Is there way like question.get(answer) or question.get([0, 2, 1])?

There's a hard coded way:
question[answer[0]][answer[1]][answer[2]];
or for any length of a array or nested array:
var question = [
[
['x', 'x', 'x'],
['x', 'x', 'x'],
['x', 'x', 'x']
],
[
['x', 'x', 'x'],
['x', 'x', 'x'],
['x', 'x', 'x']
],
[
['x', 'x', 'x'],
['x', 'x', 'x'],
['x', 'x', 'x']
]
];
var answer = [0,2,1];
var getanswer= function(answerinput,questioninput){
var val = questioninput;
answerinput.forEach(function(item){
val = val[item];
});
return val;
}
console.log(getanswer(answer,question));

Let's have some fun...
Object.prototype.getNestedValue = function(...a) {
return a.length > 1 ? (this[a[0]] !== void 0 && this[a[0]].getNestedValue(...a.slice(1))) : this[a[0]];
};
var question = [
[
['1', '2', '3'],
['4', '5', '6'],
['7', '8', '9']
],
[
['a', 'b', 'c'],
['d', 'e', 'f'],
['g', 'h', 'i']
],
[
[':', ',', '?'],
['#', '$', '%'],
['+', '!', '&']
]
];
console.log(question.getNestedValue(...[0,2,1]));
console.log(question.getNestedValue(...[1,2,0]));
console.log(question.getNestedValue(...[2,0,1]));

You could use Array#reduce, because you can use the question array as input and get the value as result by iterating the given answer array.
var question = [[['000', '001', '002'], ['010', '011', '012'], ['020', '021', '022']], [['100', '101', '102'], ['110', '111', '112'], ['120', '121', '122']], [['200', '201', '202'], ['210', '211', '212'], ['220', '221', '222']]],
answer = [0, 2, 1],
getItem = function (array, path) {
return path.reduce(function (a, p) { return a[p]; }, array);
};
console.log(getItem(question, answer));
ES6
var question = [[['000', '001', '002'], ['010', '011', '012'], ['020', '021', '022']], [['100', '101', '102'], ['110', '111', '112'], ['120', '121', '122']], [['200', '201', '202'], ['210', '211', '212'], ['220', '221', '222']]],
answer = [0, 2, 1],
getItem = (array, path) => path.reduce((a, p) => a[p], array);
console.log(getItem(question, answer));

Related

How to convert an array into an object of specific format?

Although it is a common problem but I couldn't find any lead to get the desired result. So here is the problem. I have the following array:
[
[ 'a' ]
[ 'a', 'b' ]
[ 'a', 'c' ]
[ 'a', 'c', 'd' ]
[ 'a', 'c', 'd', 'e' ]
]
And what I want as an end result is an object like this:
{
a: {
b: {},
c: { d: { e: {} } }
}
}
I don't understand which approach would be better to get this result and how to achieve it.
You need a double reduce, one for the outer array and one for the keys and the nesting objects.
var data = [['a'], ['a', 'b'], ['a', 'c'], ['a', 'c', 'd'], ['a', 'c', 'd', 'e']],
result = data.reduce((r, keys) => {
keys.reduce((o, k) => o[k] = o[k] || {}, r);
return r;
}, {});
console.log(result);

Modify object containing array based on an array which contains an object

Here are the variables:
let linked = {
related: [
[0, 'a', 'b'],
[0, 'c', 'd', 'e', 'f', 'g'],
[0, "s"],
[0, 'd'],
[0, 'g', 'n', 'h']
]
}
let hold = [{
0: 4, // 0 represents [0,'a','b']
1: 3 // 1 represents [0,'c','d','e','f','g']
},
{
3: 2, // 3 represents [0,'d']
4: 6 // 4 represents [0,'g','n', 'h']
}
];
The hold array contains two objects and each object's property represents index of link.related .
The problem is I want to add values of each hold object property to the first element of linked.related.
So the result should be:
let linked = {
related: [
[4, 'a', 'b'],
[3, 'c', 'd', 'e', 'f', 'g'],
[0, "s"],
[2, 'd'],
[6, 'g', 'n', 'h']
]
}
So I want to sum values of hold with the first element of linked.related
You can do it in 2 forEach loops
hold.forEach(x => {
Object.keys(x).forEach (y => {
linked.related[y][0] += x[y]
});
});
let linked = {
related: [
[0, 'a', 'b'],
[0, 'c', 'd', 'e', 'f', 'g'],
[0, "s"],
[0, 'd'],
[0, 'g', 'n', 'h']
]
}
let hold = [{
0: 4,
1: 3
},
{
3: 2,
4: 6
}
];
hold.forEach(x => {
Object.keys(x).forEach (y => {
linked.related[y][0] += x[y]
});
});
console.log(linked.related);
You could iterate hold and get the entries for the update.
var linked = { related: [[0, 'a', 'b'], [0, 'c', 'd', 'e', 'f', 'g'], [0, "s"], [0, 'd'], [0, 'g', 'n', 'h']] },
hold = [{ 0: 4, 1: 3 }, { 3: 2, 4: 6 }];
hold.forEach(o => Object.entries(o).forEach(([i, v]) => linked.related[i][0] += v));
console.log(linked);
.as-console-wrapper { max-height: 100% !important; top: 0; }
You can use forEach and Object.entries
let linked = {related: [[0, 'a', 'b'],[0, 'c', 'd', 'e', 'f', 'g'],[0, "s"],[0, 'd'],[0, 'g', 'n', 'h']]}
let hold =[{0: 4, 1:3},{3: 2, 4:6}]
hold.forEach(v => {
Object.entries(v).forEach(([k, v]) => {
linked.related[k][0] += v
})
})
console.log(linked)

Get coordinates of an element in multidimentional array in Javascript [duplicate]

This question already has answers here:
To find Index of Multidimensional Array in Javascript
(7 answers)
Closed 3 years ago.
I want to where is placed an element in an multidimentional array like that :
var letterVariations = [
[' ','0','1','2','3','4','5','6','7','8','9'],
['A','a','B','b','C','c','D','d','E','e',';'],
['Â','â','F','f','G','g','H','h','Ê','ê',':'],
['À','à','I','i','J','j','K','k','È','è','.'],
['L','l','Î','î','M','m','N','n','É','é','?'],
['O','o','Ï','ï','P','p','Q','q','R','r','!'],
['Ô','ô','S','s','T','t','U','u','V','v','“'],
['W','w','X','x','Y','y','Ù','ù','Z','z','”'],
['#','&','#','[','(','/',')',']','+','=','-'],
];
var coordinates = letterVariations.indexOf('u');
console.log(coordinates);
// Want to know that 'u' is 7 in the 7th array
Is it possible ?
Run a simple for loop and check if the character exists in the inner array using indexOf. return immediately once a match is found
var letterVariations = [
[' ', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9'],
['A', 'a', 'B', 'b', 'C', 'c', 'D', 'd', 'E', 'e', ';'],
['Â', 'â', 'F', 'f', 'G', 'g', 'H', 'h', 'Ê', 'ê', ':'],
['À', 'à', 'I', 'i', 'J', 'j', 'K', 'k', 'È', 'è', '.'],
['L', 'l', 'Î', 'î', 'M', 'm', 'N', 'n', 'É', 'é', '?'],
['O', 'o', 'Ï', 'ï', 'P', 'p', 'Q', 'q', 'R', 'r', '!'],
['Ô', 'ô', 'S', 's', 'T', 't', 'U', 'u', 'V', 'v', '“'],
['W', 'w', 'X', 'x', 'Y', 'y', 'Ù', 'ù', 'Z', 'z', '”'],
['#', '&', '#', '[', '(', '/', ')', ']', '+', '=', '-'],
];
function getCoordinates(array, char) {
for (let i = 0; i < array.length; i++) {
const i2 = array[i].indexOf(char);
if (i2 !== -1)
return [i, i2]
}
return undefined
}
console.log(getCoordinates(letterVariations, 'u'))
console.log(getCoordinates(letterVariations, '#'))
Note: This returns the indexes and it is zero-based. If you want [7, 7], you need to return [i+1, i2]
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf
const letterVariations = [
[' ','0','1','2','3','4','5','6','7','8','9'],
['A','a','B','b','C','c','D','d','E','e',';'],
['Â','â','F','f','G','g','H','h','Ê','ê',':'],
['À','à','I','i','J','j','K','k','È','è','.'],
['L','l','Î','î','M','m','N','n','É','é','?'],
['O','o','Ï','ï','P','p','Q','q','R','r','!'],
['Ô','ô','S','s','T','t','U','u','V','v','“'],
['W','w','X','x','Y','y','Ù','ù','Z','z','”'],
['#','&','#','[','(','/',')',']','+','=','-'],
];
function getIndexOfLetter(letter) {
return letterVariations.reduce((result, values, index) => {
if (result[0] > -1) return result;
const found = values.indexOf(letter);
return found > -1 ? [Number(index), found] : result;
}, [-1, -1])
}
console.log(getIndexOfLetter('k'))

How to merge two array in one object?

I have two array name and mark
I am trying to merge two arrays as one single object so that later I can iterate over.
Like there is a table of two column the first return name from API such as A, b, c, d and so and second return marks such as 40, 50 55, 60 and so on.
On receiving I am trying to make it as one iterable object as
finalOutput = [
0: {
A : 45
}
1: {
B: 55
}
2: {
C: 60
}
and so on...
]
I am trying to take the below approach which is not a complete solution. can you suggest me what approach I should take?
var name = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'I'];
var tName = name.split(',');
var mark = ['45', '55', '60', '65', '70', '75', '80', '85'];
var nameObj = Object.assign({}, tName );
console.log(nameObj);
var tMark = Object.assign({}, mark);
var finalOutput = [].concat(tName, tMark);
console.log('finalOutput', finalOutput);
You can simply use Array.map(), Assuming both your arrays have same length, and you want a array of objects as final output, try the following:
let names = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'I'];
let mark = ['45', '55', '60', '65', '70', '75', '80', '85'];
let result = names.map((name,index)=> ({[name] : mark[index]}));
console.log(result);
You can use Array.reduce():
const names = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'I'];
const marks = ['45', '55', '60', '65', '70', '75', '80', '85'];
const toObject = names.reduce((accum, item, i) => {
accum[item] = marks[i];
return accum;
}, {})
console.log(toObject);
Array.map() is probably more readable, but I like (and use) the reduce-object-creating pattern a lot (thanks, Wes Bos).
You might want to create function to do that, so you can reuse it:
const names = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'I'];
const marks = ['45', '55', '60', '65', '70', '75', '80', '85'];
const toObject = (toProp, toValue) => {
return toProp.reduce((accum, item, i) => {
accum[item] = toValue[i];
return accum;
}, {})
}
console.log(toObject(names, marks));

Sort Multidimensional array in descending order

I have an array that is currently sorted by the first value:
[ [ 'a', 3 ],
[ 'c', 3 ],
[ 'd', 1 ],
[ 'e', 2 ],
[ 'f', 1 ],
[ 'g', 1 ],
[ 'i', 7 ],
[ 'l', 3 ],
[ 'o', 2 ],
[ 'p', 2 ],
[ 'r', 2 ],
[ 's', 3 ],
[ 't', 1 ],
[ 'u', 2 ],
[ 'x', 1 ] ]
I would like to sort the digits in descending order to get:
[ [ 'i', 7 ],
[ 'a', 3 ],
[ 'c', 3 ],
[ 'l', 3 ],
[ 's', 3 ],
[ 'e', 2 ],
[ 'o', 2 ] ......]
Use Array.sort([compareFunction])
function comparator(a, b) {
if (a[1] > b[1]) return -1
if (a[1] < b[1]) return 1
return 0
}
myArray = myArray.sort(comparator)
edit for comment:
Here is a jslint showing it in action:
https://jsfiddle.net/49ed0Lj4/1/
The sort method in Array
var arr = [
['a', 3],
['c', 3],
['d', 1],
['e', 2],
['f', 1],
['g', 1],
['i', 7],
['l', 3],
['o', 2],
['p', 2],
['r', 2],
['s', 3],
['t', 1],
['u', 2],
['x', 1]
];
arr.sort(function(a, b) {
return b[1] - a[1]
})
Maybe you need to sort by both the English letters and number. You can change the callback function to do this.

Categories

Resources