I wanted objects like this:
[{ age: 3, area: 5 },
{ age: 4, area: 15 },
{ age: 19, area: 3 },
{ age: 16, area: 11 },
{ age: 20, area: 4 },
{ age: 6, area: 9 }]
The approach was to create new objects each time and push it inside an array.
function Numstuff(age,area) {
this.age = age,
this.area = area
}
var numObjArray = []
var createObj = new Numstuff (Math.floor(Math.random() * 20),
Math.floor(Math.random() * 20))
numObjArray.push(createObj)
But This pushes only one. How to create multiple objects and push inside an array?
You can make an array directly with Array.from() and fill it with your objects by passing a function:
function Numstuff(age,area) {
this.age = age,
this.area = area
}
// make 10 numstuffs
const num = 10
let arr = Array.from({length: num}, () => new Numstuff (Math.floor(Math.random() * 20), Math.floor(Math.random() * 20)))
console.log(arr)
What about this:
var array = [];
var obj = {};
for(var i=0;i<=10;i++){
obj = {age: i, area: Math.random()}
array.push(obj);
}
console.log(array)
Maybe with a for loop. Using you own code:
for (var i = 0; i < 9; i++) {
var createObj = new Numstuff (Math.floor(Math.random() * 20),
Math.floor(Math.random() * 20))
numObjArray.push(createObj)
}
Related
I have a problem here, with the arrays. So. I have 3 arrays:
const names = [Robert, Mark, Lindsay, Anna, Erin, Andrew]
const surnames = [Smith, Black, White, Lewis, Cooper, Hill]
const ages = [21, 14, 19, 28, 65, 31]
I must create 2 functions :
On will give me a new array with the couples man-woman (like Robert-Anna / Erin-Mark etc.);
And one must give a me a new array with the name, the surname and the age (like Robert Smith 21, Mark Black 14, etc.).
So, what I think for the first function was to do this randomly:
function getElementFromArray(arr) {
const min = 0;
const max = (arr.length);
const randIndex = Math.floor(Math.random() * (max - min));
return arr[randIndex];
}
const boyArray = Array("Robert", "Mark", "Andrew");
const boy = getElementFromArray(boyArray);
const girlArray = Array("Erin", "Anna", "Lindsay");
const girl = getElementFromArray(girlArray);
const getPair = [boy + girl];
But this is not a function, so I must to transform this into a function. And this thing gives me only one couple of Man+Woman, but i need 3 couples that must to be written in an Array form.
For the second function, i really don't now how to write it. Thinked about something like:
const nameSurnameAge = [names.slice (0, 1) + surnames.slice (0, 1) + ages.slice (0, 1)] + [names.slice (1, 2) + surnames.slice (1, 2) + ages.slice (1, 2)]
But again: this is not a function (and i need to transform this thing into a function) and it's very-very long.
Can somebody help me please?
Thank You!
Use arrays of men and women. Assuming there are an equal number of men and women.
const names = ["Robert", "Mark", "Lindsay", "Anna", "Erin", "Andrew"]
const surnames = ["Smith", "Black", "White", "Lewis", "Cooper", "Hill"]
const ages = [21, 14, 19, 28, 65, 31]
const genders = ["M", "M", "F", "F", "F", "M"]
var arrNew = [];
var people = [];
function fnBuildNewArray(){
for (var i=0; i<names.length; i++) {
people[i] = {
name: names[i],
surname: surnames[i],
age: ages[i],
gender: genders[i],
partner: "single"
};
arrNew[i] = people[i]["name"]+" "+people[i]["surname"]+" is "+people[i]["age"];
}
}
function fnBuildCouples(){
var iMen = [];
var iWomen = [];
var m=0;
var w=0;
// collect men and woman
for (var i=0; i<names.length; i++) {
if(people[i]["gender"]=="M"){
iMen[m] = i;
m++;
}
else
{
iWomen[w] = i;
w++;
}
}
// This is where the magic happens
// Shuffle the Women
let iWomenshuffled = iWomen
.map(value => ({ value, sort: Math.random() }))
.sort((a, b) => a.sort - b.sort)
.map(({ value }) => value);
var offset=0;
// assign the partners
for (var i=0; i<people.length; i++) {
if(people[i]["gender"]=="M"){
var z = iWomenshuffled[offset];
people[i]["partner"] = people[z]["name"];
people[z]["partner"] = people[i]["name"]
offset++;
}
}
}
function fnProcess(){
fnBuildNewArray();
fnBuildCouples();
console.log(JSON.stringify(arrNew));
console.log(JSON.stringify(people));
}
<button onclick="fnProcess()">Process</button>
I would like to have multiple arrays of objects like this.
E.g:
const pets = [
{
name: "cat",
age: 4
},
{
name: "dog",
age: 6
}
]
But I want to create it using a map. So I was trying something like this.
let pets = [];
pets.map((item) => {
return (
item.push({
name: "cat",
age: 4
}, {
name: "dog",
age: 6
})
)
})
By this method, I'm getting an empty array.
So assuming this is incorrect, how would I go on and make this through a map.
Please any help would be appreciated.
first of all map works by looping through an array but you have empty array let pets = []; so the loop doesn't even start ! that's why you are getting empty array
Secondly map essentially is a method through which we can create a new array with the help of an existing array so you have chosen a wrong way!
example of map
const fruits = ["Mango", "Apple", "Banana", "Pineapple", "Orange"];
console.log(fruits);
const uppercaseFruits = fruits.map((fruit)=>{
return fruit.toUpperCase(); // this thing will be added to new array in every iteration
});
console.log(uppercaseFruits);
but still ....
let pets = [""]; // an item so that loop can start
const myPets = pets.map((item) => {
return (
([{
name: "cat",
age: 4
},{
name: "dog",
age: 6
}])
)
})
console.log(myPets)
//Usage of map: for example
let array = [1, 2, 3, 4, 5];
let newArray = array.map((item) => {
return item * item;
})
console.log(newArray) // [1, 4, 9, 16, 25]
map will not change the original array, if you don't assign a value to it, the original array will never be affected
And if you want to get what you want you use RANDOM like this
//random String
function randomString(e) {
e = e || 32;
var t = "ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678",
a = t.length,
n = "";
for (i = 0; i < e; i++) n += t.charAt(Math.floor(Math.random() * a));
return n
}
//random Number
function GetRandomNum(Min,Max)
{
var Range = Max - Min;
var Rand = Math.random();
return(Min + Math.round(Rand * Range));
}
var num = GetRandomNum(10000,999999);
alert(num);
Then you can combine random strings and random numbers into a new Object through a function
In javascript I want to create an array of 20 objects containing 2 random numbers between 1 and 250. All numbers in the array I want to be unique from each other. Basically like this:
const matches = [
{ player1: 1, player2: 2 },
{ player1: 3, player2: 4 },
{ player1: 5, player2: 6 },
{ player1: 7, player2: 8 },
...
]
// all unique numbers
I have found this other method
const indexes = [];
while (indexes.length <= 8) {
const index = Math.floor(Math.random() * 249) + 1;
if (indexes.indexOf(index) === -1) indexes.push(index);
}
But this only returns an array of numbers:
[1, 2, 3, 4, 5, 6, 7, 8, ...]
You could use Array.from method to create an array of objects and then also create custom function that will use while loop and Set to generate random numbers.
const set = new Set()
function getRandom() {
let result = null;
while (!result) {
let n = parseInt(Math.random() * 250)
if (set.has(n)) continue
else set.add(result = n)
}
return result
}
const result = Array.from(Array(20), () => ({
player1: getRandom(),
player2: getRandom()
}))
console.log(result)
You can create an array of 251 elements (0-250) and preset all values to 0 to keep track of the generated elements. Once a value is generated, you mark that value in the array as 1.
Check below:
// create an array of 251 elements (0-250) and set the values to 0
let array = Array.from({ length: 251 }, () => 0);
let matches = [];
function getRandomUniqueInt() {
// generate untill we find a value which hasn't already been generated
do {
var num = Math.floor(Math.random() * 249) + 1;
} while(array[num] !== 0);
// mark the value as generated
array[num] = 1;
return num;
}
while (matches.length <= 4) {
let obj = { "player1" : getRandomUniqueInt(), "player2" : getRandomUniqueInt() };
matches.push(obj);
}
console.log(matches);
I tried to sort an array of objects. With key and value. I could able to sort with age .but I don't know how to sort with age and score from my object array
Any help will be much appreciated
Fiddle
var unsorted = [{
name: 'Peter',
age: 0,
work:'driving',
score : 20
}, {
name: 'John',
age: 0,
work:'document',
score : 30
}, {
name: 'Jess',
age: 46,
work:'teacxhing',
score :10
}, {
name: 'Alice',
age: 0,
work:'singing',
score:80
}],
sortedByAge = sortByKey(unsorted.slice(0), 'age');
/**
* Get a DOM element by ID
* #param {String} id
* #return {Object}
*/
function $dom(id) {
return document.getElementById(id);
}
/**
* Sort an array of Objects based on key
* #param {Array} array
* #param {String} key
* #returns {Array}
*/
function sortByKey(array, key) {
return array.sort(function (a, b) {
var x = a[key],
y = b[key];
if (typeof x === 'string') {
x = x.toLowerCase();
y = y.toLowerCase();
if (!isNaN(x) && !isNaN(y)) {
x = parseInt(x, 10);
y = parseInt(y, 10);
}
}
return (x > y ? -1 : (x < y ? 1 : 0));
});
}
/**
* Build a HTML String with the people their age
* #param {Array} array
* #return {String}
*/
function getPeople(array) {
for (var i = 0, len = array.length, returnString = ''; i < len; i ++) {
returnString += array[i].name + ', ' + array[i].age +',' +array[i].work+','+array[i].score+'<br/>';
}
return returnString;
}
// Update the DOM
$dom('sortedByAge').innerHTML = getPeople(sortedByAge);
You can use array#sort to sort first on age and for same age sort on score using b.age - a.age || b.score - a.score
var unsorted = [{ name: 'Peter', age: 0, work:'driving', score : 20 }, { name: 'John', age: 0, work:'document', score : 30 }, { name: 'Jess', age: 46, work:'teacxhing', score :10 }, { name: 'Alice', age: 0, work:'singing', score:80 }];
unsorted.sort((a,b) => b.age - a.age || b.score - a.score);
console.log(unsorted);
iam sure your data are incorrect.
json object are using property, e.g: {property_name1: property_value1, property_name2: property_value2}
and since your data didn't have property name, i think that you meant its an array of array:
data = [ ['workername1',1,2,32], ['workername2', 40,20,40], ['workername3', 10,50,10] ];
and you can use array sort to do that, e.g:
data.sort(function(smaller, bigger){ return bigger[3] - smaller[3] });
I have an ionic project and am using the following library:
http://gionkunz.github.io/chartist-js/index.html
Actually drawing the chart is achieved with the following:
var chart = new Chartist.Line('.ct-chart', {
series: [
{
name: 'series-1',
data: [
{x: new Date(143134652600), y: 53},
{x: new Date(143234652600), y: 40},
{x: new Date(143340052600), y: 45},
{x: new Date(143366652600), y: 40},
{x: new Date(143410652600), y: 20},
{x: new Date(143508652600), y: 32},
{x: new Date(143569652600), y: 18},
{x: new Date(143579652600), y: 11}
]
},
{
name: 'series-2',
data: [
{x: new Date(143134652600), y: 53},
{x: new Date(143234652600), y: 35},
{x: new Date(143334652600), y: 30},
{x: new Date(143384652600), y: 30},
{x: new Date(143568652600), y: 10}
]
}
]
}, {
axisX: {
type: Chartist.FixedScaleAxis,
divisor: 5,
labelInterpolationFnc: function(value) {
return moment(value).format('MMM D');
}
}
});
With a DIV:
<div class="ct-chart ct-perfect-fourth"></div>
Instead of having a hardcoded array for the series as shown above, I would like to build this dynamically through a function call.
Any example of how I might do that?
Thanks!
You could generate the data with a little randomness and some fixed variables using a generate function. It's probably also nicer to parametize the creation of your chart for easier re-creation later. Chartist also has a update() function that lets you hand it new data and options, so is especially useful for this.
JSFIDDLE
Javascript
var button = document.getElementById('button');
var options = {
axisX: {
type: Chartist.FixedScaleAxis,
divisor: 5,
labelInterpolationFnc: function(value) {
return moment(value).format('MMM D');
}
}
};
var chart; // initialise the chart variable
function createChart(){
chart = new Chartist.Line('.ct-chart', changeData(), options);
}
function updateChart(){
chart.update(changeData());
}
function changeData(){
var series = [];
// set up series ranges
var numberOfSeries = 2;
var numberOfItems = 8;
var startDate = 143134652600;
var endDate = 143579652600;
var minY = 11;
var maxY = 53;
// creates the 'step' each x-axis item should take
var dateDiff = Math.floor((endDate - startDate) / numberOfItems);
// alternatively set the step to a whole day etc. (makes endDate unnecessary)
// var dateDiff = 24 * 60 * 60 * 1000;
for(var x = 0; x < numberOfSeries; x++){
var seriesData = [];
for(var y = 0; y < numberOfItems; y++){
seriesData.push({
x: new Date(startDate + (dateDiff*y)),
y: getRandomInt(minY, maxY)
})
}
series.push({
name: 'series-'+ (x+1),
data: seriesData
});
}
// return the data to display in the chart
return {series:series};
}
/**
* Returns a random integer between min (inclusive) and max (inclusive)
* Using Math.round() will give you a non-uniform distribution!
*/
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
button.addEventListener('click', updateChart);
createChart(); // generate chart initially
HTML
<button id="button">
Change Data
</button>
<div class="ct-chart ct-perfect-fourth"></div>
This is a rough example; you could replace the input series1, series2 with an array of arrays and make the lower for-loops two wrapped loops to handle multiple series. This would also entail adding the objects to the series array in the outer loop.
For now, try something like this:
function generateJSON(series1, series2) {
var chartInternal = {
series: [
{
name: 'series-1',
data: []
},
{
name: 'series-2',
data: []
}
]
}, {
axisX: {
type: Chartist.FixedScaleAxis,
divisor: 5,
labelInterpolationFnc: function(value) {
return moment(value).format('MMM D');
}
}
};
for (var i = 0, len = series1.length; i < len; i++) {
chartInternal.series[0].data.push({x: new Date(series1[i].date), y: series1[i].y});
}
for (var i = 0, len = series2.length; i < len; i++) {
chartInternal.series[1].data.push({x: new Date(series2[i].date), y: series2[i].y});
}
return chartInternal;
}
Usage:
var series1 = [
{ date: 1234567, y:52 },
... more
];
var series2 = [
{ date: 7654321, y:52 },
... more
];
var chart = new Chartist.Line('.ct-chart', generateJSON(series1, series2))