Transform values in JavaScript array to values in an array [duplicate] - javascript

This question already has answers here:
From an array of objects, extract value of a property as array
(24 answers)
Closed 5 years ago.
Let's say I have the following Object.
const result = [{date:'2016-11-21',name:'Bob',score:0.1034947}{date:'2016-10-21',name:'Bill',score:0.2081911},{date:'2016-10-21',name:'Mary',score:0.234947},{date:'2016-10-21',name:'Bob',score:0.1034947},{date:'2016-11-21',name:'Bill',score:0.2081911},{date:'2016-11-21',name:'Mary',score:0.234947},{date:'2016-12-21',name:'Bob',score:0.1034947},{date:'2016-12-21',name:'Bill',score:0.2081911},{date:'2016-12-21',name:'Mary',score:0.234947}];
What I want to take that object and turn those values and put them in separate arrays. So for example,
dateArray = ['2016-11-21','2016-10-21', ....]
I am really quite new to JavaScript. I am trying to do it with map but not sure if I am on the right track. So thanks in advance!

var dateArray = [];
for (var index in result) {
var item = result[index];
dateArray.push(item.date);
}

You can use Array.prototype.map to transform your array to a new one by projecting every original value with the defined function.
var dateArray = result.map(function(r) {
return r.date;
});
This code literally means "take array result and make a new array dateArray of the same length where every item is a value of date property of corresponding item of result".
You can also use arrow-function, but it is only compatible with ECMAScript 6.
var dateArray = result.map(r => r.date);

Related

Best way to sort array based of different sets of data? [duplicate]

This question already has answers here:
Javascript sort array of objects using array of priority
(2 answers)
Closed 1 year ago.
var array = [{value:"13",type:"Fruit"},{value:"61",type:"Animal"},
{value:"19",type:"Fruit"},{value:"71",type:"Animal"},
{value:"12",type:"Fruit"},{value:"15",type:"Fruit"},
{value:"11",type:"Plant"},{value:"10",type:"Fruit"},
{value:"16",type:"Plant"}]
What is the best/optimized way to sort this array such that I get all elements of type Fruit first and then the elements of type Animal (by picking elements from end of array).
expectedOutput = [{value:"10",type:"Fruit"},
{value:"15",type:"Fruit"},{value:"12",type:"Fruits"},
{value:"19",type:"Fruit"},{value:"13",type:"Fruit"},
{value:"71",type:"Animal"},{value:"61",type:"Animal"},
{value:"16",type:"Plant"},{value:"11",type:"Plant"}]
Note:- I don't need to sort it Alphabetically. It must be sort depending upon the specific type.
You can store the order of the type properties in an array, then subtract the index of the type property when sorting to determine precedence:
const order = ["Fruits", "Animal"]
var array = [{value:"13",type:"Fruit"},{value:"61",type:"Animal"},
{value:"19",type:"Fruit"},{value:"71",type:"Animal"},
{value:"12",type:"Fruit"},{value:"15",type:"Fruit"}]
const sorted = array.sort((a,b) => order.indexOf(a.type) - order.indexOf(b.type))
console.log(sorted)

Javascript Take JSON string convert to array [duplicate]

This question already has answers here:
How can I convert a comma-separated string to an array?
(19 answers)
Closed 3 years ago.
*****No JQUERY*****
I have a string passed into my Javascript that looks like below. I want to convert it into an array.
I have
{"test":"1,180,35"}
I want
an array where index 0 = 1, index 1 = 180, index 2 = 35.
How would I achieve this?
Parse the string, pull out the property value for property test, split it on ,.
var input = '{"test":"1,180,35"}'
var jsObj = JSON.parse(input);
var arr = jsObj.test.split(",");
console.log(arr);
use JSON.parse() to convert a string into a json object.
But, you are looking to parse a series of numbers into an array, so what you really want is split(",")
Use the JSON object
let arr = JSON.parse('{"test":"1,180,35"}').test.split(',');
For example:
var yourData = `{"test":"1,180,35"}`
JSON.parse(yourData).split(',')

Ordering of array values to match another array ES6 [duplicate]

This question already has answers here:
Javascript custom sort algorithm according to another array
(4 answers)
Closed 6 years ago.
In a nutshell, what I'm trying to do is use the order of one array to follow the order of another...
For example... (Using ES6 React)
const orderArr = ["Daniel","Lucas","Gwen","Henry","Jasper"];
const nameArr = ["Gwen","Jasper","Daniel"];
to return
Daniel // first
Gwen // second
Jasper // third
so the new array would look like const newNameArr = ["Daniel","Gwen","Jasper"]; // following the order
orderArr is the ordered array I'd like to follow. So if any other arrays come about (nameArr) they should follow the order of orderArr.
Is this even possible?
One way would be to filter out the ones that don't appear in both arrays, using orderArr as the base. This ensures they'll appear in the same order as they appear in orderArr.
const orderArr = ["Daniel","Lucas","Gwen","Henry","Jasper"];
const nameArr = ["Gwen","Jasper","Daniel"];
const newNameArr = orderArr.filter((x) => nameArr.indexOf(x) > -1);
document.write('<pre>' + JSON.stringify(newNameArr, null, 2) + '</pre>');

javascript for loop and array pushing [duplicate]

This question already has answers here:
Array.push() makes all elements the same when pushing an object [duplicate]
(2 answers)
Dates changing when I change another date [duplicate]
(1 answer)
Closed 26 days ago.
I'm trying to create an array of date objects starting from a certain date up till today.
Here's the code I have:
var beginning = new Date("04,06,2013");
var dates = [];
var today = new Date();
while (beginning < today){
var x = beginning;
console.log(x);
dates.push(x);
beginning.setDate(beginning.getDate()+1)
}
for (var i in dates) {
console.log(dates[i]);
}
In the while loop I see the correct dates incrementing but when I print out the dates in the array at the last for loop I see all the dates that are pushed being today's date.
Any ideas?
What your code does is push a whole bunch of references to the exact same Date object. So, you have an array full of all the same Date object and each time you change that object, all elements in the array just point to the same object so they will all appear to change.
When you push an object into an array or assign an object to a variable, it does not make a copy, it pushes a reference to it (think of it like a pointer in other languages). To push different date objects for each iteration of the loop, you'd have to create a new date object each time through the loop and push that.
In javascript, assigning an object or an array to any variable (which includes pushing it into an array) only assigns a reference to that object or array, not a copy. This is a common issue that bits most people coming up to speed on javascript.
You can make a new date object each time through the loop like this:
var beginning = new Date("04,06,2013");
var dates = [];
var today = new Date(), x;
while (beginning < today){
x = new Date(beginning.getTime());
console.log(x);
dates.push(x);
beginning.setDate(beginning.getDate()+1)
}
You're only working with one single Date instance throughout all that code.
To create a copy of a Date, do this:
x = new Date(beginning.getTime());
Then call the .setDate() method to move it forward.
The setters on JavaScript Date instances change the object. They don't create a new one.

Javascript array returns length as 0 always even there are elements in it [duplicate]

This question already has answers here:
Why does a string index in an array not increase the 'length'?
(7 answers)
Closed 9 years ago.
I have a javascript array like below with several elements in it. When I try to read the length of the array I am always getting 0 as the length. Can any one tell me why this is like this.
My array is like this:
var pubs = new Array();
pubs['b41573bb'] =['Albx Swabian Alb Visitor Guide','','15.12.2007 09:32:52',['0afd894252c04e1d00257b6000667b25']];
pubs['6c21a507'] =['CaSH','','29.05.2013 14:03:35',['30500564d44749ff00257b7a004243e6']];
You seem to be confusing an array with object. What you have is not an array. An array can only have integer indexes. In your example you seem to be using some b41573bb and 6c21a507 which are not integers, so you don't have an array. You have a javascript object with those properties. An array would have looked like this:
var pubs = new Array();
pubs[0] = ['Albx Swabian Alb Visitor Guide','','15.12.2007 09:32:52',['0afd894252c04e1d00257b6000667b25']];
pubs[1] = ['CaSH','','29.05.2013 14:03:35',['30500564d44749ff00257b7a004243e6']];
Now when you call .length you will get the correct number of elements (2).
The reported length is correct, because the array is empty.
When you use a string (that doesn't represent a number) with the bracket syntax, you are not putting items in the array, you are putting properties in the array object.
try this
<script type="text/javascript">
var pubs = new Array();
var b41573bb = new Array();
var c6c21a507 = new Array();
b41573bb.push['Albx Swabian Alb Visitor Guide', '', '15.12.2007 09:32:52', ['0afd894252c04e1d00257b6000667b25']];
c6c21a507.push['CaSH', '', '29.05.2013 14:03:35', ['30500564d44749ff00257b7a004243e6']];
pubs.push(b41573bb);
pubs.push(c6c21a507);
alert(pubs.length);

Categories