Combining two arrays into one object in javascript - javascript

I want to combine two arrays into one Object with name "data"
Didn't find any efficient way
arrays:
var N =[ 1, 2, 3];
var s =[ a, b, c];
combine them into object:
var data= { s:[ a, b, c], N: [ 1, 2, 3 ] };

The easiest way would be:
const N = [1, 2, 3];
const s = ['a', 'b', 'c'];
const data = { s, N };
This is equivalent to:
const N =[ 1, 2, 3];
const s = ['a', 'b', 'c'];
const data = { s: s, N: N };
Note: I used const since the variables aren't reassigned.

Do it this way:
var N =[ 1, 2, 3];
var s =[ a, b, c];
var obj = {N, s};

var N =[ 1, 2, 3];
var s =[ 'a', 'b', 'c'];
var data = {s, N};
console.log(data);

Just pass your arrays (N and s) as variables to your new object.
You can do this in few ways:
let myObject = { N: N, s: s }
If you do this way you can type any other key. For example:
let myObject = { firstArray: N, secondArray: s }
and now you can access to N and s arrays as myObject.firstArray etc
Use short notation:
let myObject = { N, s }
This code will look up for variables N and s and write it inside your new object, which will give the same result as let myObject = { N: N, s: s }

Related

Map an array to create a new array of pairs

I have two separate arrays and I'm trying to create a new nested array that has values grouped together.
Can I use the map() method and pair each item inside the map method?
There is a similar question here: Map an array of arrays
However, he context is different because I don't have a nested array to begin with.
var letters = [a, b, c];
var numbers = [1, 2, 3];
var lettersAndNumbers = letters.map((letter) => {
numbers.forEach((number) => {
return letter, number;
);
});
// lettersAndNumbers = [[a, 1], [b, 2], [c, 3]]
Thank you for any tips, hints, or solutions!
To do this, use the following
var letters = ['a','b','c'];
var numbers = [1, 2, 3];
var letterAndNumbers = letters.map((letter,index) => {
return [letter,numbers[index]];
})
And if you print it, you will receive the following output
console.log(letterAndNumbers)
[ [ 'a', 1 ], [ 'b', 2 ], [ 'c', 3 ] ]
The second parameter of .map() is Index. Make use of it for retrieve a numbers[i] by that iterating index:
const letters = ["a", "b", "c"];
const numbers = [1, 2, 3];
const lettersAndNumbers = letters.map((a, i) => [a, numbers[i]]);
console.log(lettersAndNumbers)
// lettersAndNumbers = [[a, 1], [b, 2], [c, 3]]
I would use a map but here is a reduce just for the sake of it.
var letters = ['a', 'b', 'c'];
var numbers = [1, 2, 3];
var lettersAndNumbers = (letters, numbers) => letters.reduce((results, letter, index) => {
results.push([letter, numbers[index]]);
return results;
}, []);
console.log(lettersAndNumbers(letters, numbers));

JavaScript split and merge arrays by conditions

I have an array like [a, b, c, d] and I want to split it into 2 arrays like [a, b] and [c, d] and then merge it to have final result like [[a, b],[c, d]]. Is it possible to do without for loop?
You can use slice and push method like this
var arr = ['a', 'b', 'c', 'd'];
let index = 2;
let result = [];
result.push(arr.slice(0, index));
result.push(arr.slice(index))
console.log(result);
let arr = [0, 1, 9, 10, 8];
let arr2 = arr.slice(1,3);
let resultArr = [];
if(arr2[1] > 1){
resultArr.push(99);
}
else{
resultArr.push(100);
}
console.log(resultArr)
You might like something like this:
a = 8;
b = { some: 'say'};
c = 'life';
d = true;
let o = {
'a': [a, b, c, d],
'a1': [],
'a2': []
}
nSwitchBefore = 2;
o.a.forEach(function(item, i) {
i < nSwitchBefore ? this.a1.push(item) : this.a2.push(item) ;
}.bind(o));
console.log(o);
Within the function block there is room for extra handling your array items. Like filtering or special treatment of certain types, using all conditions you want.
yes without loop you can do this But you should know at what index you have to split the array.
var arr = ['a', 'b', 'c', 'd'];
var indexToSplit = arr.indexOf('c');
var first = arr.slice(0, indexToSplit);
var second = arr.slice(indexToSplit + 1);
var final = [first, second]
console.log(final);
I found another solution for this issue, without writing loops
Lodash Chunk does this logic
_.chunk(['a', 'b', 'c', 'd'], 2);
// => [['a', 'b'], ['c', 'd']]
https://lodash.com/docs/

Assign multiple values to an object in one go as with variable assignment in JavaScript

It is possible to do:
let a = 1,
b = 3,
c = 9;
Is it also possible to do:
obj.a = 1,
b = 2,
c = 3;
This is still very readable, but a lot less typing, then writing obj a lot of times.
If the variables are already defined, you can use shorthand property names to define the object in one go, without any repetition:
const obj = { a, b, c };
You can assign the defined variables using shorthand property names
let a = 1,
b = 3,
c = 9;
let obj = {a,b,c}
console.log(obj)
If there exists a relation between the property names and the values then one can write a compact object definition using map. Otherwise one can just initialize the object with names and values.
// function
var obj = {};
['a', 'b', 'c'].map((x, i) => (obj[x] = i));
console.log(obj);
// no function
var obj1 = {a: 1, b: 2, c: 4};
console.log(obj1);
If the variables are not already assigned, you could use Object.assign:
const obj = Object.assign({}, { a: 1, b: 2, c: 3 });
console.log(obj);
Otherwise, use ES6 shorthand property notation:
const [a, b, c] = [1, 2, 3];
const obj = { a, b, c };
console.log(obj);
You can do this (if object is re-assignable ex: let NOT const ):
obj = {...obj, a : 1,
b : 2,
c: 3,
}
Thank you :)

How to remove array value with reference to another array

I have two arrays which contains equal length:
var a = [a, b,c,d,e];
var b = [1,2,3,4,5];
I have another variable 'C' which contains one the value of array a
var c = "d";
How do I remove '4' in another array 'b' based on the value of var C.
Final values required:
finala = [a,b,c,e];
finalb = [1,2,3,5];
removeda = d;
removedb = 4;
You could use Array#indexOf for the index and use Array#splice for both arrays.
var a = ['a', 'b', 'c', 'd', 'e'],
b = [1, 2, 3, 4, 5],
c = 'd',
index = a.indexOf(c),
removeda = a.splice(index, 1)[0],
removedb = b.splice(index, 1)[0];
console.log(a);
console.log(b);
console.log(removeda);
console.log(removedb);
.as-console-wrapper { max-height: 100% !important; top: 0; }
There you go.
Removing elements from both arrays, and storing what elements you removed:
var a = ['a', 'b','c','d','e'],
b = [1,2,3,4,5],
c = "d",
index = a.indexOf(c);
var removedA = a.splice(index, 1)[0];
var removedB = b.splice(index, 1)[0];
console.log(a);
console.log(removedA)
console.log(b);
console.log(removedB)
Use Array#splice and Array#indexOf methods.
var a = ['a', 'b', 'c', 'd', 'e'];
var b = [1, 2, 3, 4, 5];
var c = "d";
// get index of eleemnt in array `a`
var i = a.indexOf(c);
// remove element and store them in variable
var removeda = a.splice(i, 1)[0],
removedb = b.splice(i, 1)[0];
console.log(a, b, removeda, removedb)
This should do the work
var index = a.indexOf(c)
var removeda = a.splice(index, 1)[0];
var removedb = b.splice(index, 1)[0];

lodash - Group/sum two arrays into object

I have two arrays (one of keys and one of values) that I want to group into an object with summing the values when keys are identical.
var keys = ['a', 'b', 'a', 'c'];
var values = [1, 2, 2, 3];
I have tryed using lodash zibObject() but there is not way to sum the value with this function. I guess using zipWith() would be the solution, but I dont know how to sum.
var grouped = _.zipWith(keys, values, function(a,b){
return {a: b}; // not summing: [{a: 1}, {b: 2}, {a, 2}, {c: 3}]
});
but what I want is:
var result = {
a: 3,
b: 2,
c: 3
};
What would be the proper way to achieve that with lodash?
without lodash or underscore
var keys = ['a', 'b', 'a', 'c'];
var values = [1, 2, 2, 3];
var grouped = {};
if (keys.length !== values.length) throw "array don't match!!"
for (var i = 0, len = keys.length; i < len; i++) {
grouped[keys[i]] = grouped[keys[i]] + values[i] || values[i];
}
document.getElementById('final').innerHTML = JSON.stringify(grouped);
<pre id="final"></pre>
_.reduce(keys, function(result, key, index){
result[key] = result[key] ? result[key] + values[index] : values[index];
return result;
}, {})
Use _.reduce using an object as the initial value:
const keys = ['a', 'b', 'a', 'c'];
const values = [1, 2, 2, 3];
// If `acc[c]` doesn't exist set it to zero
// then add one to it.
const out = _.reduce(keys, (acc, c, i) => {
acc[c] ??= 0;
acc[c] += values[i];
return acc;
}, {});
console.log(out);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.21/lodash.min.js"></script>
But you may as well use native JS for this in 2022.
const keys = ['a', 'b', 'a', 'c'];
const values = [1, 2, 2, 3];
const out = keys.reduce((acc, c, i) => {
acc[c] ??= 0;
acc[c] += values[i];
return acc;
}, {});
console.log(out);
Or even just a simple loop
const keys = ['a', 'b', 'a', 'c'];
const values = [1, 2, 2, 3];
const out = {};
for (const [i, key] of keys.entries()) {
out[key] ??= 0;
out[key] += values[i];
}
console.log(out);
Additional documentation
Logical nullish assignment

Categories

Resources