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
I have mapsOrder array and mapsData array of objects:
let mapsOrder = [1,2,1,3];
let mapData = [
{
id: 1,
gates: [
{
toId: 2,
coords: {
x: 2,
y: 42
}
},
{
toId: 3,
coords: {
x: 9,
y: 4
}
}
]
},
{
id: 2,
gates: [
{
toId: 1,
coords: {
x: 6,
y: 5
}
}
]
},
{
id: 3,
gates: [
{
toId: 1,
coords: {
x: 2,
y: 1
}
}
]
}
]
What I want to achieve is in loop basing on mapsOrder where mapsOrder array values are ids in mapData, designate gates to next map.
So we have loop that iterate 4 times and when:
loop index is 1 current map is 1 next map is 2 and gates to next are coords: { x: 2, y: 42 }
loop index is 2 current map is 2 next map is 1 and gates to next are coords: { x: 6, y: 5 }
loop index is 3 current map is 1 next map is 3 and gates to next are coords: { x: 9, y: 4 }
loop index is 4 current map is 3 next map is 1 and gates to next are coords: { x: 2, y: 1 }
last loop iteration see next map as first of mapsOrder array. I tried to do it myself by first determineting the id of next map like so:
for(let i = 0; i < mapsOrder.length; i++) {
let nextMap;
let currentMapId = mapData[mapsOrder[i] - 1].id;
if(i === mapsOrder.length - 1) {
nextMap = mapData[0].id
} else {
nextMapId = mapData[mapsOrder[i]].id;
}
console.log('Current map is: ', currentMapId, 'and the next map id is:', nextMapId)
console.log('break-----')
}
but this console incorrect ids, demo
If you don't care about the original array then just use shift to get the next gate (shift will remove the gate from the array thus the next gate will be available when the object is encountered again). Use find to find the object from the array:
let result = mapsOrder.map(id =>
mapData.find(o => o.id == id).gates.shift().coords
);
You may want to check if find actually finds something and the gates array contains something before using shift, here is a safer way:
let result = mapsOrder.map(id => {
let obj = mapData.find(o => o.id == id);
if(obj && obj.gates.length) { // if we found an object with the same id and that object still have gates
return obj.gates.shift().coords; // return the coords of the first gate and remove the gate from the array
} // otherwise, throw an error or something
});
No altering:
Instead of using shift from the previous example, we'll just use an object to track the gate index from the gates array:
let nextGateIndex = Object.create(null); // create a prototypeless object to track the next gate index for each object
let result = mapsOrder.map(id => {
let obj = mapData.find(o => o.id == id);
let index;
if(nextGateIndex[id] == undefined) {
index = 0;
} else {
index = nextGateIndex[id] + 1;
}
nextGateIndex[id] = index;
if(obj && index < obj.gates.length) {
return obj.gates[index].coords;
} // throw error or something
});
If follow your description your loop should look like. Seems that you wand to use id and toId but using array indexes. It can be a good idea to replace arrays with objects.
Demo
for(let i = 0; i < mapsOrder.length; i++) {
let nextMap;
let currentMapId = mapsOrder[i];
if(i === mapsOrder.length - 1) {
nextMapId = mapsOrder[0]
} else {
nextMapId = mapsOrder[i + 1];
}
let filteredMapData = mapData.filter(f => f.id == currentMapId);
let filteredGates = filteredMapData.length > 0 ? filteredMapData[0].gates.filter(f => f.toId == nextMapId) : [];
console.log('Current map is: ', currentMapId, 'and the next map id is:', nextMapId, 'gates:', filteredGates.length == 0 ? "no gates": filteredGates[0].coords)
console.log('break----')
}
I would recommend the filter() function for javascript arrays as it is super quick. This function will return an array filled with items from original matching some criteria (in this case, objects having the desired id).
for (let i = 0; i < mapsOrder.length; i++) {
console.log(mapData.filter(mapDataItem => mapDataItem.id === mapsOrder[i]))
}
Newb here with a basic question. Here is my object:
{TestOne: 12, TestTwo: 6, TestThree: 4, TestFour: 2}
I've looped through it using a for-in loop and grabbed the properties and displayed it in my UI like so:
TestOne: 12
TestTwo: 6
TestThree: 4
TestFour: 2
I need to be able to display this by giving each item a numerical ranking (1,2,3,4...etc) and then displaying them by that ranking (corresponding to their actual order). In other words, what my users need to see on the screen is:
TestOne: 4
TestTwo: 3
TestThree: 2
TestFour: 1
Not 12,6,4,2, etc. This is all new to me but I've been trying to figure out the best way to implement this and have not found anything that I understand to this point.
Here is my code. I feel like this should be easy but it is super frustrating!
var rank = "";
var title = objArrayTwo[i].Title;
var summary ={};
summary = groupBy(objArrayTwo);
for (var prop in summary) {
if (summary.hasOwnProperty(prop)) {
if(title == `${prop}`){
rank = `${summary[prop]}`;
}
}
}
function groupBy(items){
var result= {};
var sum;
$.each(items, function(index, item) {
sum = result[item.RequestName] || 0;
result[item.RequestName] = sum + parseInt(item.Rank);
});
return result;
}
var obj = {TestOne: 12, TestTwo: 6, TestThree: 4, TestFour: 2};
// sort the array
var arr = Object.entries(obj);
arr.sort((a, b) => a[1] - b[1]);
// enumerate the array the index would be the rank
var arr_with_rank = arr.map((data, index) => [data[0], index+1]).reverse()
arr_with_rank.forEach(x => console.log(x[0] + ": " + x[1]));
ES5 solution
var resultDataObject = {
TestOne: 12,
TestTwo: 6,
TestThree: 4,
TestFour: 2
};
var descendingSort = function(a, b) {
return resultDataObject[b] - resultDataObject[a]
};
var sortedResultKeys = Object.keys(resultDataObject).sort(descendingSort);
var resultWithRank = sortedResultKeys.map(function(k, i) {
return {
title: k,
score: resultDataObject[k],
rank: i + 1
};
})
console.log(resultWithRank)
I have mutlriple objects called stations. Each station has a property called money.
stations[0].money = 2000
stations[1].money = 500
stations[2].money = 1200
stations[3].money = 2200
I want to create an array of stations indexes (0,1,2 and 3 in this example) but sorted by ammount of money each station has ascending by money.
So I want to have:
var moneyArray = [1, 2, 0, 3]
what is the most elegant way to do it?
You can start with a normal array of indices (loop-generated, preferably) and sort that by the value of the object at the respective index in your stations array:
[0, 1, 2, 3].sort(function(ai, bi) {
return stations[ai].money - stations[bi].money;
})
You may have a look here: Sorting with map
// the array to be sorted
var stations = [
{ money: 2000 },
{ money: 500 },
{ money: 1200 },
{ money: 2200 },
];
// temporary array holds objects with position and sort-value
var mapped = stations.map(function (el, i) {
return { index: i, value: el.money };
})
// sorting the mapped array containing the reduced values
mapped.sort(function (a, b) {
return a.value - b.value;
});
// container for the resulting order
var result = mapped.map(function (el) {
return stations[el.index];
});
// get the wanted keys
var keys = mapped.map(function (el) {
return el.index;
});
document.write('<pre>' + JSON.stringify(result, 0, 4) + '</pre>');
document.write('<pre>' + JSON.stringify(keys, 0, 4) + '</pre>');
By using a Temp variable you can do it this way. Else if you can afford to modify the main data then the temp variable can be eliminated.
var stations = [{money :2000},{money :500},{money :1200},{money :2200}]
var tempArray = stations.slice();
tempArray.forEach(function (value, i) {
value.index = i;
});
tempArray.sort(function(a, b){return a.money-b.money});
var finalResult = tempArray.map(function(a) {return a.index;});
document.write(JSON.stringify(finalResult));
For example, if I have these arrays:
var name = ["Bob","Tom","Larry"];
var age = ["10", "20", "30"];
And I use name.sort() the order of the "name" array becomes:
var name = ["Bob","Larry","Tom"];
But, how can I sort the "name" array and have the "age" array keep the same order? Like this:
var name = ["Bob","Larry","Tom"];
var age = ["10", "30", "20"];
You can sort the existing arrays, or reorganize the data.
Method 1:
To use the existing arrays, you can combine, sort, and separate them:
(Assuming equal length arrays)
var names = ["Bob","Tom","Larry"];
var ages = ["10", "20", "30"];
//1) combine the arrays:
var list = [];
for (var j = 0; j < names.length; j++)
list.push({'name': names[j], 'age': ages[j]});
//2) sort:
list.sort(function(a, b) {
return ((a.name < b.name) ? -1 : ((a.name == b.name) ? 0 : 1));
//Sort could be modified to, for example, sort on the age
// if the name is the same. See Bonus section below
});
//3) separate them back out:
for (var k = 0; k < list.length; k++) {
names[k] = list[k].name;
ages[k] = list[k].age;
}
This has the advantage of not relying on string parsing techniques, and could be used on any number of arrays that need to be sorted together.
Method 2: Or you can reorganize the data a bit, and just sort a collection of objects:
var list = [
{name: "Bob", age: 10},
{name: "Tom", age: 20},
{name: "Larry", age: 30}
];
list.sort(function(a, b) {
return ((a.name < b.name) ? -1 : ((a.name == b.name) ? 0 : 1));
});
for (var i = 0; i<list.length; i++) {
alert(list[i].name + ", " + list[i].age);
}
For the comparisons,-1 means lower index, 0 means equal, and 1 means higher index. And it is worth noting that sort() actually changes the underlying array.
Also worth noting, method 2 is more efficient as you do not have to loop through the entire list twice in addition to the sort.
http://jsfiddle.net/ghBn7/38/
Bonus Here is a generic sort method that takes one or more property names.
function sort_by_property(list, property_name_list) {
list.sort((a, b) => {
for (var p = 0; p < property_name_list.length; p++) {
prop = property_name_list[p];
if (a[prop] < b[prop]) {
return -1;
} else if (a[prop] !== a[prop]) {
return 1;
}
}
return 0;
});
}
Usage:
var list = [
{name: "Bob", age: 10},
{name: "Tom", age: 20},
{name: "Larry", age: 30},
{name: "Larry", age: 25}
];
sort_by_property(list, ["name", "age"]);
for (var i = 0; i<list.length; i++) {
console.log(list[i].name + ", " + list[i].age);
}
Output:
Bob, 10
Larry, 25
Larry, 30
Tom, 20
You could get the indices of name array using Array.from(name.keys()) or [...name.keys()]. Sort the indices based on their value. Then use map to get the value for the corresponding indices in any number of related arrays
const indices = Array.from(name.keys())
indices.sort( (a,b) => name[a].localeCompare(name[b]) )
const sortedName = indices.map(i => name[i]),
const sortedAge = indices.map(i => age[i])
Here's a snippet:
const name = ["Bob","Tom","Larry"],
age = ["10", "20", "30"],
indices = Array.from(name.keys())
.sort( (a,b) => name[a].localeCompare(name[b]) ),
sortedName = indices.map(i => name[i]),
sortedAge = indices.map(i => age[i])
console.log(indices)
console.log(sortedName)
console.log(sortedAge)
This solution (my work) sorts multiple arrays, without transforming the data to an intermediary structure, and works on large arrays efficiently. It allows passing arrays as a list, or object, and supports a custom compareFunction.
Usage:
let people = ["john", "benny", "sally", "george"];
let peopleIds = [10, 20, 30, 40];
sortArrays([people, peopleIds]);
[["benny", "george", "john", "sally"], [20, 40, 10, 30]] // output
sortArrays({people, peopleIds});
{"people": ["benny", "george", "john", "sally"], "peopleIds": [20, 40, 10, 30]} // output
Algorithm:
Create a list of indexes of the main array (sortableArray)
Sort the indexes with a custom compareFunction that compares the values, looked up with the index
For each input array, map each index, in order, to its value
Implementation:
/**
* Sorts all arrays together with the first. Pass either a list of arrays, or a map. Any key is accepted.
* Array|Object arrays [sortableArray, ...otherArrays]; {sortableArray: [], secondaryArray: [], ...}
* Function comparator(?,?) -> int optional compareFunction, compatible with Array.sort(compareFunction)
*/
function sortArrays(arrays, comparator = (a, b) => (a < b) ? -1 : (a > b) ? 1 : 0) {
let arrayKeys = Object.keys(arrays);
let sortableArray = Object.values(arrays)[0];
let indexes = Object.keys(sortableArray);
let sortedIndexes = indexes.sort((a, b) => comparator(sortableArray[a], sortableArray[b]));
let sortByIndexes = (array, sortedIndexes) => sortedIndexes.map(sortedIndex => array[sortedIndex]);
if (Array.isArray(arrays)) {
return arrayKeys.map(arrayIndex => sortByIndexes(arrays[arrayIndex], sortedIndexes));
} else {
let sortedArrays = {};
arrayKeys.forEach((arrayKey) => {
sortedArrays[arrayKey] = sortByIndexes(arrays[arrayKey], sortedIndexes);
});
return sortedArrays;
}
}
See also https://gist.github.com/boukeversteegh/3219ffb912ac6ef7282b1f5ce7a379ad
If performance matters, there is sort-ids package for that purpose:
var sortIds = require('sort-ids')
var reorder = require('array-rearrange')
var name = ["Bob","Larry","Tom"];
var age = [30, 20, 10];
var ids = sortIds(age)
reorder(age, ids)
reorder(name, ids)
That is ~5 times faster than the comparator function.
It is very similar to jwatts1980's answer (Update 2).
Consider reading Sorting with map.
name.map(function (v, i) {
return {
value1 : v,
value2 : age[i]
};
}).sort(function (a, b) {
return ((a.value1 < b.value1) ? -1 : ((a.value1 == b.value1) ? 0 : 1));
}).forEach(function (v, i) {
name[i] = v.value1;
age[i] = v.value2;
});
You are trying to sort 2 independet arrays by only calling sort() on one of them.
One way of achieving this would be writing your own sorting methd which would take care of this, meaning when it swaps 2 elements in-place in the "original" array, it should swap 2 elements in-place in the "attribute" array.
Here is a pseudocode on how you might try it.
function mySort(originals, attributes) {
// Start of your sorting code here
swap(originals, i, j);
swap(attributes, i, j);
// Rest of your sorting code here
}
inspired from #jwatts1980's answer, and #Alexander's answer here I merged both answer's into a quick and dirty solution;
The main array is the one to be sorted, the rest just follows its indexes
NOTE: Not very efficient for very very large arrays
/* #sort argument is the array that has the values to sort
#followers argument is an array of arrays which are all same length of 'sort'
all will be sorted accordingly
example:
sortMutipleArrays(
[0, 6, 7, 8, 3, 4, 9],
[ ["zr", "sx", "sv", "et", "th", "fr", "nn"],
["zero", "six", "seven", "eight", "three", "four", "nine"]
]
);
// Will return
{
sorted: [0, 3, 4, 6, 7, 8, 9],
followed: [
["zr", th, "fr", "sx", "sv", "et", "nn"],
["zero", "three", "four", "six", "seven", "eight", "nine"]
]
}
*/
You probably want to change the method signature/return structure, but that should be easy though. I did it this way because I needed it
var sortMultipleArrays = function (sort, followers) {
var index = this.getSortedIndex(sort)
, followed = [];
followers.unshift(sort);
followers.forEach(function(arr){
var _arr = [];
for(var i = 0; i < arr.length; i++)
_arr[i] = arr[index[i]];
followed.push(_arr);
});
var result = {sorted: followed[0]};
followed.shift();
result.followed = followed;
return result;
};
var getSortedIndex = function (arr) {
var index = [];
for (var i = 0; i < arr.length; i++) {
index.push(i);
}
index = index.sort((function(arr){
/* this will sort ints in descending order, change it based on your needs */
return function (a, b) {return ((arr[a] > arr[b]) ? -1 : ((arr[a] < arr[b]) ? 1 : 0));
};
})(arr));
return index;
};
I was looking for something more generic and functional than the current answers.
Here's what I came up with: an es6 implementation (with no mutations!) that lets you sort as many arrays as you want given a "source" array
/**
* Given multiple arrays of the same length, sort one (the "source" array), and
* sort all other arrays to reorder the same way the source array does.
*
* Usage:
*
* sortMultipleArrays( objectWithArrays, sortFunctionToApplyToSource )
*
* sortMultipleArrays(
* {
* source: [...],
* other1: [...],
* other2: [...]
* },
* (a, b) => { return a - b })
* )
*
* Returns:
* {
* source: [..sorted source array]
* other1: [...other1 sorted in same order as source],
* other2: [...other2 sorted in same order as source]
* }
*/
export function sortMultipleArrays( namedArrays, sortFn ) {
const { source } = namedArrays;
if( !source ) {
throw new Error('You must pass in an object containing a key named "source" pointing to an array');
}
const arrayNames = Object.keys( namedArrays );
// First build an array combining all arrays into one, eg
// [{ source: 'source1', other: 'other1' }, { source: 'source2', other: 'other2' } ...]
return source.map(( value, index ) =>
arrayNames.reduce((memo, name) => ({
...memo,
[ name ]: namedArrays[ name ][ index ]
}), {})
)
// Then have user defined sort function sort the single array, but only
// pass in the source value
.sort(( a, b ) => sortFn( a.source, b.source ))
// Then turn the source array back into an object with the values being the
// sorted arrays, eg
// { source: [ 'source1', 'source2' ], other: [ 'other1', 'other2' ] ... }
.reduce(( memo, group ) =>
arrayNames.reduce((ongoingMemo, arrayName) => ({
...ongoingMemo,
[ arrayName ]: [
...( ongoingMemo[ arrayName ] || [] ),
group[ arrayName ]
]
}), memo), {});
}
You could append the original index of each member to the value, sort the array, then remove the index and use it to re-order the other array. It will only work where the contents are strings or can be converted to and from strings successfuly.
Another solution is keep a copy of the original array, then after sorting, find where each member is now and adjust the other array appropriately.
I was having the same issue and came up with this incredibly simple solution. First combine the associated ellements into strings in a seperate array then use parseInt in your sort comparison function like this:
<html>
<body>
<div id="outPut"></div>
<script>
var theNums = [13,12,14];
var theStrs = ["a","b","c"];
var theCombine = [];
for (var x in theNums)
{
theCombine[x] = theNums[x] + "," + theStrs;
}
var theSorted = theAr.sort(function(a,b)
{
var c = parseInt(a,10);
var d = parseInt(b,10);
return c-d;
});
document.getElementById("outPut").innerHTML = theS;
</script>
</body>
</html>
How about:
var names = ["Bob","Tom","Larry"];
var ages = ["10", "20", "30"];
var n = names.slice(0).sort()
var a = [];
for (x in n)
{
i = names.indexOf(n[x]);
a.push(ages[i]);
names[i] = null;
}
names = n
ages = a
Simplest explantion is the best, merge the arrays, and then extract after sorting:
create an array
name_age=["bob#10","Tom#20","Larry#30"];
sort the array as before, then extract the name and the age, you can use # to reconise where
name ends and age begins. Maybe not a method for the purist, but I have the same issue and this my approach.