Creating javascript object without fieldname - javascript

Hi I'm trying to create an object in JS which is like this
{'0':{1,2,3,4},'1':{1,2,3,4}, '2':{1,2,3,4}}
but I don't know how to create the {1,2,3,4} part.
These objects have to be created from something this :
[{'value': '{1,2,3,4,5}', 'id': 0, 'type':'node'}]
here is how I do it for the fieldname:
var domain={};
nodes.forEach(function(node){
if(node.type == "node")
domain[node.id]= node.value;
});
but node.value gives me String I don't want it to be string. I want to be in the form of {1,3,4.5}.
I appreciate any help

All properties of an object must have a name. However, you can use an array instead (note that to be truly considered JSON, the property names must be double-quoted string literals):
var myObj = {
"0": [1, 2, 3, 4],
"1": [1, 2, 3, 4],
"2": [1, 2, 3, 4]
};
In fact the, whole object can be expressed as a 2-dimensional array:
var myObj = [ [1, 2, 3, 4],
[1, 2, 3, 4],
[1, 2, 3, 4] ];
And you can access it's values like this:
myObj[1][2]; // 3

Related

JS pushing value into an Object with string key and array values

I have an object with a string type key, and an array type value, the object looks like this
myObj = { a: [1, 2, 3], b: [5. 6], c:[9] }
I want to add a integer inside the array of a certain key, let's say for example I want add the number 7 inside the array of key a, so the object becomes myObj = { a: [1, 2, 3, 7], b: [5, 6], c: [9] }
I tried doing something like myObj["a"].push(7);, but this completely changed the structure of myObj.
How should I implement this to accomplish my goal?
const myObj = { a: [1, 2, 3], b: [5, 6], c:[9] }
myObj["a"].push(7);
console.log(myObj)
Use follow as code:
const myObj = { a: [1, 2, 3], b: [5, 6], c:[9] }
myObj.a.push(7);
console.log(myObj)
I've Tried These:
let myObj = {a: [1, 2, 3], b: [5, 6], c:[9]};
myObj.a.push(7); //Worked Correctly Will Return length of "a" Array
myObj["a"].push(7); //Worked

Create a sorted array by mistake using .map()

I tried to make something that works as Set() using a couple tools that I learned. It worked, but I noticed a bug: it sorted my array! Can explain me someone why, please?
Here's my code:
function uniteUnique(...arr) {
let array = arr.flat()
let newArr = [];
console.log(array) // [ 1, 3, 2, 5, 2, 1, 4, 2, 1 ]
let myMap = array
.map(elem => {
if (!newArr.includes(elem))
return newArr.push(elem)
})
.filter(Boolean)
console.log(myMap) // [ 1, 2, 3, 4, 5 ]
}
uniteUnique([1, 3, 2], [5, 2, 1, 4], [2, 1]);
I know that for you might be too simple, but I ask so I can understand what is happening here.
console.log(myMap) // [ 1, 2, 3, 4, 5 ]
The result of your log is the number of pushed elements but accidentally, you thought they are sorted.
Also, if you return the mapped list you will end up with an array that contains an integer and boolean values. Instead of this, you need to return newArr.
Your code will be like this :
function uniteUnique(...arr) {
let flattedArray = arr.flat()
let set = [];
flattedArray.forEach(elem => !set.includes(elem) && set.push(elem))
return set
}
const set = uniteUnique([1, 3, 2], [5, 2, 1, 4], [2, 1]);
console.log(set)
in your code MyMap holds your newArr length as array.push returns the length of your array
so every time it returns the count:
for example if you tried to run this code
let newArr = []
console.log(newArr.push(20)) // the output is 1
and that's what your myMap holds => the length of your newArr
so if you want the filtered array you should use newArr
let array = [ 1, 3, 2, 5, 2, 1, 4, 2, 1 ]
let newArr = [];
let myMap = array.map(elem => {
if (!newArr.includes(elem))
return newArr.push(elem)
}).filter(Boolean)
console.log(newArr) //[1, 3, 2, 5, 4]

array data type manipulation

I have an array of arrays of objects.
so it looks something like
[[{}{}],[{}{}{}],[{}{}], [{}{}{}{}]]...etc
I need to loop through each object in this array. Problem is that would require a nested for loop, which isn't bad but I was wondering if there is any way I could use the spread operator when I'm putting it in the original array.
outerArray.push(...innerArray), something along the lines of that. That didn't work but is there something similar?
You can use Array.prototype.flat to convert a nested array, into a flattened array
var arr1 = [1, 2, [3, 4]];
arr1.flat();
// [1, 2, 3, 4]
var arr2 = [1, 2, [3, 4, [5, 6]]];
arr2.flat();
// [1, 2, 3, 4, [5, 6]]
var arr3 = [1, 2, [3, 4, [5, 6]]];
arr3.flat(2);
// [1, 2, 3, 4, 5, 6]
For older browsers, you can refer to other answers
Just adding another option here that doesn't require passing the depth in:
const deepFlatten = arr =>
[].concat(...arr.map(v => (Array.isArray(v) ? deepFlatten(v) : v)))
call with deepFlatten(outerArray)

Is JavaScript's array map prototype a little off?

I was playing around with JavaScript's array prototype map and I don't understand why I'm getting the following values:
console.log(
[1,2,2,5,6].map(function(a,b){
return a+b;
})
); /*This returns [ 1, 3, 4, 8, 10 ]*/
Shouldn't the above code return [1,3,4,7,11] ?
Here's another snippet which shows that elements in the array are added sequentially and are correct at least I believe so.
console.log(
[1,2,3,4,5,6].map(function(a,b){
return a+b;
})
); /*[ 1, 3, 5, 7, 9, 11 ]*/
This is just a curious question more along the lines of why the first snippet of code seems.
It's because map passes you the value as the first parameter and the index as the second. So, what you're adding is: 1 + 0, 2+1, 2+2, 5+3, etc.
Your a value is the value out of the array: 1, 2, 2, 5, 6
Your b value is actually an index, not a value out of the array: 0, 1, 2, 3, 4
Let's sum:
[1, 2, 2, 5, 6] // Your values
+ [0, 1, 2, 3, 4] // Indices
-----------------
[1, 3, 4, 8,10] // Result
[1, 2, 3, 4, 5, 6] // Your values
+ [0, 1, 2, 3, 4, 5] // Indices
--------------------
[1, 3, 5, 7, 9,11] // Result
The results are correct.
I think you are confusing map with reduce:
var arr = [];
[1,2,2,5,6].reduce(function(a,b){
arr.push(a+b);
return b;
}, 0);
arr; // [1, 3, 4, 7, 11]
[0, 1, 2, 2, 5] // Values returned in previous iteration
+ [1, 2, 2, 5, 6] // Your values
-----------------
[1, 3, 4, 7,11] // Result
so the first parameter 'a' is value and the 'b' is index. so adding together it shows the corect value only. so 'a' contains [1, 2, 2, 5, 6] and 'b' contains [0, 1, 2, 3, 4]

Concatenate an unknown number of arrays in Javascript/NodeJS

I have a function in one of my controllers where I populate an array of references to a document, which, when populated, have embedded arrays themselves.
Here's an example:
The mongoose populate function gives me an array of objects. Within each of those objects is an array:
[{ name: Test, array: [ 1, 2, 3, 4, 5 ] }, { name: TestAgain, array: [1, 2, 3, 4, 5] }, { name: Test^3, array: [1, 2, 3, 4, 5]}, {...
The desired output would be:
[1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 1, 2, 3, 4, 5, ...]
I need to concatenate all of the "arrays" within the populated references. How can I do this without knowing how many arrays there are?
For reference, here is (generally) what my function looks like:
exports.myFunctionName = function ( req, res, next )
Document.findOne({ 'document_id' : decodeURIComponent( document_id )}).populate('array_containing_references').exec(function( err, document)
{
//Here I need to concatenate all of the embedded arrays, then sort and return the result as JSON (not worried about the sorting).
});
Assuming your input is in the document variable, try this:
var output = document.reduce(function (res, cur) {
Array.prototype.push.apply(res, cur.array);
return res;
}, []);
Or this:
var output = [];
document.forEach(function(cur) {
Array.prototype.push.apply(output, cur.array);
});
You want to take each document and do something with a property from it. Sounds like a great use case for Array.prototype.map!
map will get each document's array value and return you an array of those values. But, you don't want a nested array so we simply use Array.prototype.concat to flatten it. You could also use something like lodash/underscore.js flatten method.
var a = [
{ name: 'test1', array: [1, 2, 3, 4, 5]},
{ name: 'test2', array: [1, 2, 3, 4, 5]},
{ name: 'test3', array: [1, 2, 3, 4, 5]}
];
var results = Array.prototype.concat.apply([], a.map(function(doc) { return doc.array; }));
document.body.innerHTML = results;

Categories