Convert Object array to String Array - javascript

I have an Object array that looks like the following:
var array = [
{'id':1,'description':test},
{'id':2,'description':test},
{'id':3,'description':test}
]
And I want to convert it to look like this:
var newArray = [
1, 2, 3
]
So it's basically taking the object array, extracting the id's out of the objects, and creating a new array that contains the id's that were extracted. Is there a way to do this in one line? Even better if a new array doesn't have to get created and array is just updated.

var test ="sai";
var array = [
{'id':1,'description':test},
{'id':2,'description':test},
{'id':3,'description':test}
]
console.log(array.map(function(obj){return obj.id}))

iterate the array using foreach and populate newArray
var newArray = [];
array.forEach(funtion(element){
newArray.push(element.id);
});
console.log( newArray );

array.map(function (item) {
return item["id"];
}
If you'd like to have anew instance of the mapped array:
var newarray = [];
array.forEach(function (item) {
newarray.push(item["id"]);
}

array.map(function(element) {return element.id})
OP Requirement: better if array is just updated
array = array.map(function(element) {return element.id})

Related

Converting an object to array

I have a object like this
users = {
user1:{name: bob,
age:23},
user2:{name:rob,
age:24},
user3:{name:jay,
age:30}}
How to convert this object into an array like [user1:{name: bob,age:23},user2{name:rob,age:24},user3:{name:jay,
age:30}]
Simple, map the Object.keys array of your object to the array you want. I added in the object key as the "id" field.
const users = {
user1:{name: 'bob',
age:23},
user2:{name:'rob',
age:24},
user3:{name:'jay',
age:30}};
const arr = Object.keys(users).map(key => ({id: key, ...users[key]}));
console.log(arr);
the map solution is more up to date but sometimes old vanilla js is easier to understand
const users = {user1:{name:'bob',age:23},user2:{name:'rob',age:24},user3:{name:'jay',age:30}};
var myArray=[];
for(let i =1;i<4;i++){
var user={['user'+i]:users['user'+i]} //create your object
myArray.push(user); //add it to array
}
console.log(myArray[0]['user1']) // remember arrays are indexed []
console.log(myArray[1]['user2'])
console.log(myArray[2]['user3'])
console.log(myArray);
.as-console-wrapper{min-height:100%;})

Convert Array of arrays of objects to Array of Arrays

I have to following array:
var arr1 = [
[{n:"0.1",m:"m.0",other:"eg1"}],
[{n:"1.1",m:"m.1",other:"eg2"}],
[{n:"2.1",m:"m.2",other:"eg3"}]
];
And I would like to convert it to an array of arrays, as follows:
var arr1 = [
["0.1","0"],
["1.1","1"],
["2.1","2"]
];
I would like to convert to the other array only a few properties, not all of them.
Any idea how I can do this?
PS: I was using flatMap from another post but it does not work as it does not exist in Edge.
Assuming that the second value in each subarray is coming from the number after the period from the m key, you could use the map function to accomplish this:
var arr1 = [
[{n:"0.1",m:"m.0",other:"eg1"}],
[{n:"1.1",m:"m.1",other:"eg2"}],
[{n:"2.1",m:"m.2",other:"eg3"}]
];
var newArray = arr1.map(x => [x[0].n, x[0].m.split('.')[1]]);
console.log(newArray);
For next time you have to put your attempts.
this is the solution for your problem
var arr1 = [
[{n:"0.1",m:"m.0",other:"eg1"}],
[{n:"1.1",m:"m.1",other:"eg2"}],
[{n:"2.1",m:"m.2",other:"eg3"}]
];
arr1 = arr1.map(currentArray=>{
const item = currentArray.shift();
return [item.n,item.m.replace( /^\D+/g, '')]
});

Giving an array of indexes, how to push items from one array to another depending on the indexes that are specified?

I am trying to push items from one Array to another depending on the order that is supplied. Essentially i have a 2d array with a name and a price :
var myArray = [['Apples',22],['Orange',55],['Berry',23]];
Another array with the order it should be in :
var myOrder = [0,2,1];
My resulting array would look like this :
var finalArray = [['Apples',22],['Berry',23],['Orange',55]]
My initial thought process was to loop through myArray and loop through myOrder , store the object temporary at a specified index in myOrder then push to final array. I think i am over thinking it a bit, i made several attempts but with no luck whatsoever. Any help would be greatly appreciated!
This is a simple map() that doesn't require anything else
var myArray = [['Apples',22],['Orange',55],['Berry',23]];
var myOrder = [0,2,1];
let final = myOrder.map(i => myArray[i])
console.log(final)
The optimal way appears to me to be:
Initialize empty finalArray
Loop over your myOrder array
2.1. Push myArray[index] to finalArray
Like so:
let finalArray = [];
for(let index of myOrder) {
finalArray.push(myArray[index]);
}
Review the for...of syntax if you're not familiar with it.
You can use splice to insert so long as the same number of elements are present in both the arrays.
You iterate over the myOrder array and then use splice, to which the index of the new array is the current value of the iteration and then use array present in the index position of myArray
var myArray = [['Apples',22],['Orange',55],['Berry',23]];
var myOrder = [0,2,1];
var finalArray = [];
myOrder.forEach(function(val, index) {
finalArray.splice(val, 0, myArray[index]);
});
console.log(finalArray);
Easy enough using .reduce:
var myArray = [['Apples',22],['Orange',55],['Berry',23]];
var myOrder = [0,2,1];
function reorder(array, order) {
return order.reduce((newArray, orderIndex) => {
newArray.push(array[orderIndex]);
return newArray;
}, []);
}
console.log(reorder(myArray, myOrder))
function reorder(arr, order) {
return order.map(function(i) {
return arr[i];
});
}
var myArray = [['Apples',22],['Orange',55],['Berry',23]];
var myOrder = [0,2,1];
reorder(myArray, myOrder); // => [["Apples",22],["Berry",23],["Orange",55]]
One of way solving this will be
var myArray = [['Apples',22],['Orange',55],['Berry',23]];
var myOrder = [0,2,1];
var finalArray;
for (x in myOrder) {
finalArray[x] = myArray[myOrder[x]];
}
This is a beginning level solution. Also you use libraries available for java script such as underscore.js(http://underscorejs.org/) for such operations on Array and Object.
Also you can use ECMA 6, for doing this which will reduce your line of coding.
Example-
var myArray = [['Apples',22],['Orange',55],['Berry',23]];
var myOrder = [0,2,1];
let finalArray = myOrder.map(i => myArray[i])
This is the new way of coding in javascript.
In my point of view, it will be easy if you learn latest version of Java script(ECMAscript 6)

Javascript array inside array

I am creating an array like this:
var groupUserCounter=[];
groupUserCounter["asd"]=1;
groupUserCounter["asd2"]=2;
var groupC=[];
for(var key in groupUserCounter) {
groupC.push(key);
}
console.log(groupC);
Output:
Array [ "asd", "asd2" ]
But I need something like this:
Array [ ["asd"], ["asd2"] ]
How can I achive this?
When you push your key into groupC, you have to push a key array, not just the value.
var groupUserCounter=[];
groupUserCounter["asd"]=1;
groupUserCounter["asd2"]=2;
var groupC=[];
for(var key in groupUserCounter) {
groupC.push([key]);
}
console.log(groupC);
EDIT
A more elegant way is using .keys() and .map() method.
var groupUserCounter=[];
groupUserCounter["asd"]=1;
groupUserCounter["asd2"]=2;
var groupC = Object.keys(groupUserCounter).map(function(elm){
return [elm]
});
console.log(groupC);
$.makeArray() functions returns any object into a native Array.just like below
$.each(groupUserCounter, function(index, value) {
groupC.push($.makeArray( value));
});
console.log(groupC);//something like this what u expected Array [ ["asd"], ["asd2"] ]

How to add new objects to an array

I have to write a function that will create an array filled with the indicated number of objects that represent three "types" of these objects.
WITHOUT using for or while loop and not doing that manually?
I don't know how can I add these objects into the array.
I'm choosing the type of object by random, but how can I add them to the array?
these are the objects:
var bestaccount=function(){
var amount=0;
this.pay=function(howmuch){amount+=howmuch;};
this.widthdraw=function(howmuch){amount-=howmuch;};
this.saldo=function(){return amount;};
};
var toGive= function(){
var amount=0;
this.pay=function(howmuch){amount+=howmuch;};
this.saldo=function(){return amount;};
};
var toWithdraw=function(){
var amount=0;
this.withdraw=function(howmuch){amount-=howmuch;};
this.saldo=function(){return amount;};
};
For example there are 3 toWithdraw objects, 1 bestAccount and 1 toGive. I want them all in one array.
EDIT:
Sorry, I was using completely wrong functions.
If anyone needs it, I'm doing it with apply().
Here's the code:
function fillArrayWithNumbers(n) {
arr = Array.apply(null, Array(n));
tabl= arr.map(function (x, i) { return new objects[Math.floor(Math.random()*objects.length)](); });
return tabl;
}
Sorry, but no stress guys. Everyone started somehow.
Now that you have answered your own question, I see that I have misinterpreted it. Anyway, here is how to add objects to an array:
You can add new elements to an array with push like this:
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.push("Kiwi");
Now, instead of an array with strings, you want an array with objects. So you can first create the object like this:
var myObject = {numberOfGive: 1, numberOfWithdraw: 3, numberOfBestAccount: 1};
And then push it to your array:
var myArray = [];
myArray.push(myObject);
Source
here's my solution:
var objects =[bestaccount,toGive,toWithdraw];
function fillArrayWithNumbers(n) {
arr = Array.apply(null, Array(n));
tabl= arr.map(function (x, i) { return new objects[Math.floor(Math.random()*objects.length)](); });
return tabl;
}
Thanks for response.

Categories