2D array into an object - javascript

Essentially, I would like to make:
var current = [
[4, 'socks'],
[2, 'pants'],
[1, 'shoes'],
[5, 'hats']
];
Into this:
var current = {
socks: 4,
pants: 2,
shoes: 1,
hats: 5
};

If you want to iterate through a collection and return a single object then reduce() is your tool:
var current = [
[4, 'socks'],
[2, 'pants'],
[1, 'shoes'],
[5, 'hats']];
current.reduce(
function(m,c) {
m[c[1]] = c[0];
return m;
}, {})
// Object {socks: 4, pants: 2, shoes: 1, hats: 5}
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce

You can loop through the arrays in the array and add them as properties in the object:
var result = {};
for (var i = 0; i < current.length; i++) {
result[current[i][1]] = current[i][0];
}
Demo:
var current = [
[4, 'socks'],
[2, 'pants'],
[1, 'shoes'],
[5, 'hats']];
var result = {};
for (var i = 0; i < current.length; i++) {
result[current[i][1]] = current[i][0];
}
// show result in snippet
document.write(JSON.stringify(result));

With [].forEach.call():
var current = [
[4, 'socks'],
[2, 'pants'],
[1, 'shoes'],
[5, 'hats']
];
var res = {};
[].forEach.call(current, function(el) {
res[el[1]] = el[0];
});
console.log(res);
var html = document.getElementById("result");
result.innerHTML = JSON.stringify(res);
<div id="result"></div>

Related

Multiplying Two Arrays

I am trying to multiply two arrays, of the same length and create a third array from it.
I've tried loops and I think a nested loop would be the way forward.
Below is my attempt, that multiplied out the whole array
var one = [1, 2, 3, 4, 5];
var two = [1, 2, 3, 4, 5];
//var partOne = one.length
var partOne = []
for(var i=0; i<one.length;i++) {
for(var j=0;j<two.length;j++) {
partOne.push({value:one[i] * two[i]});
}
}
Looking for something similar to the below;
var a = [3, 5]
var b = [5, 5]
//answer
var c = [15, 25]
function multiply(a, b) {
var c = [];
for (var i=0; i<a.length;i++) {
c.push(a[i]*b[i]);
}
return c;
}
var a = [3, 5 ];
var b = [5, 5 ];
var c = multiply(a, b);
console.log(c);
var a = [3, 5 ]
var b = [5, 5 ]
var c = []
for (var i=0; i<a.length;i++) {
c.push(a[i]*b[i]);
}
console.log(c);
let a = [3, 5];
let b = [5, 5];
// x is each element from a
// i is index of a
let c = a.map((x, i) => { return x * b[i]; });
returns
// Array [ 15, 25 ]

How to log only the elements from second level array from a multidimentional array

I have the following array and I need to log only the elements from the second level array from it.
var myArr = [1, 2, 3, [10, 11,[1321,3213,[321321, true], "ha"], 133], 4, 5];
The output should be:
mySecondArr = [10, 11, 133];
with the following code, the output will include the third grade and so on arrays
for(i = 0; i < myArr.length; i++){
if (typeof(myArr[i]) == 'object'){
console.log(myArr[i])
}
}
Thank you in advance!
You can filter by Array.isArray:
const findInnerArr = outerArr => outerArr.find(item => Array.isArray(item));
const myArr = [1, 2, 3, [10, 11,[1321,3213,[321321, true], "ha"], 133], 4, 5];
const output = findInnerArr(myArr)
.filter(item => !Array.isArray(item));
console.log(output);
For more 2nd levels, you could filter by array and filter the inner arrays out and concat the result to a single array.
var array = [1, 2, 3, [10, 11, [1321, 3213, [321321, true], "ha"], 133], ['foo', 'bar', ['baz']], 4, 5],
result = array
.filter(Array.isArray)
.map(a => a.filter(b => !Array.isArray(b)))
.reduce((r, a) => r.concat(a));
console.log(result);
#CertainPerformance answer looks much better, but still for your reference, this is your way.
var newArr = [];
for(i = 0; i < myArr.length; i++){
if (typeof(myArr[i]) == 'object'){
// second level found
for(var j=0;j<myArr[i].length;j++){
if(typeof(myArr[i][j]) != 'object'){
newArr.push(myArr[i][j]);
}
}
break;
}
}
Use Array.filter, Array.reduce and Array.isArray
let myArr = [1, 2, 3, [10, 11,[1321,3213,[321321, true], "ha"], 133], 4, 5, ['this', 'should', ['not'], 'be', 'part', 'of', 'result']];
/* 1. Get all the items that are array from myArr
** 2. Reduce that array with pushing non-Array into the result. */
let result = myArr.filter((a) => Array.isArray(a)).reduce((a,c) => [...a, ...c.filter((d) => !Array.isArray(d))], []);
console.log(result);
Recursive mode get any level of the array
function getElementsAt(_array, level, currentLvl=1){
if(level< 1) throw("level must be > 1");
if(typeof _array === "undefined") throw("Array or level is undefined");
hasSubLvl = _array.some(e=>{
return e instanceof Array;
});
if(currentLvl!== level){
const __array = _array.filter(e =>{
return e instanceof Array;
})[0];
return getElementsAt(__array, level, currentLvl+1);
}
else{
return !hasSubLvl ? _array : _array.filter(e =>{
return !(e instanceof Array);
});
}
}
const arr = [1, 2, 3, [10, 11,[1321,3213,[321321, true], "ha"], 133], 4, 5];
const myArr = getElementsAt(arr, 2);
console.log(myArr, "result");
#CertainPerformance did it in the most cleanest and sweetest way.
I've used for-loops to find your result.
var myArr = [1, 2, 3, [10, 11,[1321,3213,[321321, true], "ha"], 133], 4, 5];
let ans = []
for(let i=0;i<myArr.length; i++) {
if(Array.isArray(myArr[i])) {
for(let j=0;j<myArr[i].length;j++) {
if(!Array.isArray(myArr[i][j])) {
ans.push(myArr[i][j]);
}
}
}
}
console.log(ans);
var myArr = [1, 2, 3, [10, 11,[1321,3213,[321321, true], "ha"], 133], 4, 5];
myArr = myArr.find((data) => typeof(data) ==='object');
myArr = myArr.filter((data) => typeof(data) != 'object');
console.log(myArr);
I've come with a simple solution to my own question, easy to understand for beginers :) thank you all for the help!
var myArr = [1, 2, 3, [10, 11, [1321, 3213, [321321, true], "ha"], 133], 4, 5];
for (i = 0; i < myArr.length; i++) {
if (typeof (myArr[i]) == 'object') {
var secondArr = arrayulMeu[i]
for (j = 0; j < secondArr.length; j++) {
if (typeof (secondArr[j]) != 'object') {
console.log(secondArr[j])
}
}
}
}

how to implement list iteration in javascript

I have written this code
var items = [
[1, 2],
[3, 4],
[5, 6]
];
function listiteration(list, fromrows, torows, col) {
var newl = list; //making a copy of list
var iterla = [];
for (i = fromrows; i <= torows; i++) {
iterla[i] = [];
for (j = col; j <= col; j++) {
iterla[i][j] = newl[i][j];
}
}
return iterla;
}
console.log(listiteration(items, 1, 2, 1));
result should be
[[4],[6]]
but getting
[ <1 empty item>, [ <1 empty item>, 4 ], [ <1 empty item>, 6 ] ]
how to solve this
You don't need the second for loop. Just create a new list, iterate over the rows and use push function to add the current rows col-th element into the array.
const items = [[1, 2], [3, 4], [5, 6]];
function listiteration(list, fromRows, toRows, col) {
const newList = [];
for (let i = fromRows; i <= toRows; i++) {
newList.push([list[i][col]]);
}
return newList;
}
const newItems = listiteration(items, 1, 2, 1);
console.log(newItems);
You can do this with slice() and map() methods.
var items = [[1, 2], [3, 4], [5, 6]];
function f(list, start, end, col) {
return list.slice(start, end + 1).map(e => [e[col]])
}
const result = f(items, 1, 2, 1)
console.log(result)
You can also add check for arrays.
var items = [[1, 2], 'a', [5, 6], [1, 2]];
function f(list, start, end, col) {
return list
.slice(start, end + 1)
.map(e => Array.isArray(e) ? [e[col]] : e)
}
const result = f(items, 1, 3, 1)
console.log(result)
A simpler approach
var items = [[1, 2], [3, 4], [5, 6]];
function listiteration(list, fromrows, torows, col) {
var ret = [];
for (var i = fromrows; i <= torows; i++) {
ret.push(list[i][col]);
}
return ret;
}
console.log(listiteration(items, 1, 2, 1));
This would be the solution
var items = [ [1, 2], [3, 4], [5, 6] ];
function listiteration(list, start, end, col) {
var result = [];
for ( i = start; i <= end; i++ ) {
result.push( [ list[ i ][ col ] ] )
}
return result;
}
console.log(listiteration(items, 1, 2, 1));
Other answers have given you different ways of doing this, and that's great.
But for learning purposes I've fixed the bug in the one you have done.
All you forgot to do was offset the arrays back to zero..
iterla[i - fromrows][j - col] = newl[i][j];
Example below..
var items = [
[1, 2],
[3, 4],
[5, 6]
];
function listiteration(list, fromrows, torows, col) {
var newl = list; //making a copy of list
var iterla = [];
for (i = fromrows; i <= torows; i++) {
iterla[i - fromrows] = [];
for (j = col; j <= col; j++) {
iterla[i - fromrows][j - col] = newl[i][j];
}
}
return iterla;
}
console.log(listiteration(items, 1, 2, 1));
var items = [
[1, 2],
[3, 4],
[5, 6]
];
function listiteration(list, fromrows, torows, col) {
var newArr = list.splice(fromrows, torows);
var newResult =[];
newArr.map(value=>{
newResult.push([value[col]]);
});
return newResult;
}
console.log(listiteration(items, 1, 2, 1));

Merge two of one dimensional array into two dimensional array javascript

I have n (but for now, let say just two) of one dimensional arrays like this image of my console :
And I want to merge these two arrays by the corresponding key and put it into two dimensional array :
The result is something like :
[["1 279 226,08" , "127"],[null , null],["-188 033,77", "154"],..... so on ......]
And the list of one dimensional array is dynamic, it could be more than 2 arrays.
So example if I have 3 arrays, then my two dimensional array would look like :
[ ["1 279 226,08" , "127" , "blabla"], [null , null , "blabla"], ["-188 033,77", "154", "blabla"], ..... so on ......]
Any ideas of implementing it would be appreciate.
You could transpose the array with a nested loop and switch the indices for assigning the values.
var array = [["1 279 226,08", null, "-188 033,77"], ["127", null, "154"], ["blabla", "blabla", "blabla"]],
result = array.reduce(function (r, a, i) {
a.forEach(function (b, j) {
r[j] = r[j] || [];
r[j][i] = b;
});
return r;
}, []);
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Since all of your arrays have the same size, you can loop just on the lenght of the first array, i.e. a.
Then we pass to appendArrays the single value of a , b, ..., and we return the an array to push into merged
var a = ["123", null, "ciao"]
var b = ["321", 1, "pippo"]
var c = ["111", 5, "co"]
var merged = []
for (i = 0; i < a.length; i++) {
merged.push(appendArrays(a[i], b[i], c[i]));
}
console.log(merged);
function appendArrays() {
var temp = []
for (var i = 0; i < arguments.length; i++) {
temp.push(arguments[i]);
}
return temp;
}
This should do what you want.
var arr1 = [1, 2, 3, 4, 5, 6];
var arr2 = [6, 5, 4, 3, 2, 1];
var arr3 = [7, 8, 9, 10, 11, 5];
var arr4 = [12, 34, 55, 77, 22, 426];
var arrCollection = [arr1, arr2, arr3, arr4];
// if array sizes are variable.
// if not max = arrCollection[0].length will do
var max = Math.max.apply(Math, arrCollection.map(function(a) {
return a.length;
}));
var arrFinal = [];
for (let i = 0; i < max; i++) {
var arr = [];
arrCollection.forEach(function(a) {
arr.push(a[i]);
});
arrFinal.push(arr);
}
console.log(arrFinal);
You can create this with two forEach() loops.
var arr1 = [[1, 2], [3, 4], [5, 6]];
var arr2 = [[1, 2, 3], [4, 5, 6], [7, 8], [9, 10, 12, 14]];
let merge = function(arr) {
var result = [];
arr.forEach(function(e, i) {
e.forEach(function(a, j) {
if (!result[j]) result[j] = [a];
else result[j].push(a)
})
});
return result;
}
console.log(JSON.stringify(merge(arr1)))
console.log(JSON.stringify(merge(arr2)))

Group identical values in array

I have an array that has some values inside, and I wish to return another array that has the value grouped in to their own arrays.
So the result I am trying to achieve is something like this:
var arr = [1,1,2,2,2,3,3,4,4,4,4,5,6]
var groupedArr =[[1,1],[2,2,2],[3,3],[4,4,4,4],[5],[6]]
This proposal works with Array#reduce for sorted arrays.
var arr = [1, 1, 2, 2, 2, 3, 3, 4, 4, 4, 4, 5, 6],
groupedArr = arr.reduce(function (r, a, i) {
if (!i || a !== r[r.length - 1][0]) {
return r.concat([[a]]);
}
r[r.length - 1].push(a);
return r;
}, []);
document.write('<pre>' + JSON.stringify(groupedArr, 0, 4) + '</pre>');
Here you go. By the way, this works with unsorted array as well.
var arr = [1, 1, 2, 2, 2, 3, 3, 4, 4, 4, 4, 5, 6]
var grpdArr = [];
while(arr.length > 0){
var item = arr[0];
grpdArr.push(arr.filter(function(val) {
return val === item;
}));
arr = arr.filter(function(val){return val!==item});
}
//console.log(arr, grpdArr);
Well this should do. Pretty straight forward..,
You get the elements and then remove them.
With forEach and temporary array
var arr = [1, 1, 2, 2, 2, 3, 3, 4, 4, 4, 4, 5, 6];
var temp = [];
var res = [];
arr.forEach(function(e) {
if (temp.slice(-1) == e) temp.push(e);
else {
temp = [e];
res.push(temp);
}
});
document.write(JSON.stringify(res));
This may not be the most optimal version but should do. This also works for unsorted arrays.
function abc(arr) {
var newObj = new Object();
for (var i in arr) {
if (typeof newObj[arr[i]] == 'undefined') {
newObj[arr[i]] = new Array();
}
newObj[arr[i]].push(arr[i]);
}
var groupedArr = new Array();
for (i in newObj) {
groupedArr.push(newObj[i]);
}
return groupedArr;
}
console.log(abc([1, 1, 2, 2, 3, 3, 3, 4, 1]));
This is the most straightforward in my mind:
var arr = [1,1,2,2,2,3,3,4,4,4,4,5,6];
var grouped = {};
var groupedArr = [];
//accumulate the values in an object, each key is an array
for (var i = 0; i < arr.length; i++) {
if (!grouped[arr[i]]) grouped[arr[i]] = [];
grouped[arr[i]].push(arr[i]);
}
//loop through all the keys in the object and push the arrays to the master array
var keys = Object.keys(grouped);
for (var i = 0; i < keys.length; i++) {
groupedArr.push(grouped[keys[i]]);
}
console.log(groupedArr);
I think you could use the code below:
var arr = [1,1,2,2,2,3,3,4,4,4,4,5,6]
var groupedArray = [];
var temp = arr.sort();
var tempArray = [arr[0]];
for(var i = 0; i < temp.length - 1; ++i){
if(temp[i] == temp[i + 1]){
tempArray.push(temp[i + 1]);
}else{
groupedArray.push(tempArray);
tempArray = [temp[i + 1]];
}
}
groupedArray.push(tempArray);
Now the groupedArray will contain the Result

Categories

Resources