Filter JSON with NodeJS - javascript

I have a JSON array containing several objects. I would like to return objects containing a certain value. For example, I would like to return
[
service_wog: {
count: 48,
popular: false,
code: 33,
price: 20,
id: 76,
service: 'WOG',
slug: 'wog'
},
service_gojoy: {
count: 48,
popular: false,
code: 33,
price: 20,
id: 77,
service: 'GoJoy',
slug: 'gojoy'
}
]
How do I return the object that contains 'gojoy' in slug?
I tried the following way:
let u = Object.values(a);
u.filter(i => i.slug === 'gojoy');
It doesn't seem to be working... Did I misunderstand how the filter() works?

No, it seems that you're using filter correctly.
However, what are you using as an input:
[
service_wog: {
count: 48,
popular: false,
code: 33,
price: 20,
id: 76,
service: 'WOG',
slug: 'wog'
},
service_gojoy: {
count: 48,
popular: false,
code: 33,
price: 20,
id: 77,
service: 'GoJoy',
slug: 'gojoy'
}
]
it's not a valid array, but an object.
So instead of [ and ] - { and } should be used:
{
service_wog: {
count: 48,
popular: false,
code: 33,
price: 20,
id: 76,
service: 'WOG',
slug: 'wog'
},
service_gojoy: {
count: 48,
popular: false,
code: 33,
price: 20,
id: 77,
service: 'GoJoy',
slug: 'gojoy'
}
}
So eventually:
const a = {
service_wog: {
count: 48,
popular: false,
code: 33,
price: 20,
id: 76,
service: 'WOG',
slug: 'wog'
},
service_gojoy: {
count: 48,
popular: false,
code: 33,
price: 20,
id: 77,
service: 'GoJoy',
slug: 'gojoy'
}
}
let u = Object.values(a);
console.log(u.filter(i => i.slug === 'gojoy'));

Related

For loop accessing an array of objects with array's

const bankAccounts = [
{
id: 1,
name: "Susan",
balance: 100.32,
deposits: [150, 30, 221],
withdrawals: [110, 70.68, 120],
},
{ id: 2, name: "Morgan", balance: 1100.0, deposits: [1100] },
{
id: 3,
name: "Joshua",
balance: 18456.57,
deposits: [4000, 5000, 6000, 9200, 256.57],
withdrawals: [1500, 1400, 1500, 1500],
},
{ id: 4, name: "Candy", balance: 0.0 },
{ id: 5, name: "Phil", balance: 18, deposits: [100, 18], withdrawals: [100] },
];
function getAllWithdrawals(bankAccounts) {
let newArr = [];
for (let acc of bankAccounts) {
if (acc.withdrawals) {
newArr.push(acc.withdrawals)
} else if (!acc.withdrawals) {
newArr.push(0);
}
}
return newArr;
}
I am getting access to the array objects. But how do I get into the objects with the array of withdrawals with varying amounts, add them all and print that in the blank array "newArr"? Do I need another for loop? My overall goal is to iterate through the objects check which ones pass that have withdrawals array. If they do not have a withdrawals array I pass 0. The objects that do have withdrawals I need to iterate through those and add them up and push the total of the withdrawal array into the "newArr".
Here is a functional programming solution that uses map reduce:
const bankAccounts = [ { id: 1, name: "Susan", balance: 100.32, deposits: [150, 30, 221], withdrawals: [110, 70.68, 120], }, { id: 2, name: "Morgan", balance: 1100.0, deposits: [1100] }, { id: 3, name: "Joshua", balance: 18456.57, deposits: [4000, 5000, 6000, 9200, 256.57], withdrawals: [1500, 1400, 1500, 1500], }, { id: 4, name: "Candy", balance: 0.0 }, { id: 5, name: "Phil", balance: 18, deposits: [100, 18], withdrawals: [100] }, ];
function getAllWithdrawals(bankAccounts) {
return bankAccounts.map(obj => {
return obj.withdrawals ? obj.withdrawals.reduce((sum, num) => sum + num, 0) : 0;
});
}
console.log(getAllWithdrawals(bankAccounts));
Output:
[
300.68,
0,
5900,
0,
100
]
Docs:
Intro to map reduce: https://medium.com/poka-techblog/simplify-your-javascript-use-map-reduce-and-filter-bd02c593cc2d
.map(): https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map
.reduce(): https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Reduce
Here is an enhanced version where you pass the deposits or withdrawls key into the function:
const bankAccounts = [ { id: 1, name: "Susan", balance: 100.32, deposits: [150, 30, 221], withdrawals: [110, 70.68, 120], }, { id: 2, name: "Morgan", balance: 1100.0, deposits: [1100] }, { id: 3, name: "Joshua", balance: 18456.57, deposits: [4000, 5000, 6000, 9200, 256.57], withdrawals: [1500, 1400, 1500, 1500], }, { id: 4, name: "Candy", balance: 0.0 }, { id: 5, name: "Phil", balance: 18, deposits: [100, 18], withdrawals: [100] }, ];
function getSums(bankAccounts, key) {
return bankAccounts.map(obj => {
return obj[key] ? obj[key].reduce((sum, num) => sum + num, 0) : 0;
});
}
console.log({
deposits: getSums(bankAccounts, 'deposits'),
withdrawals: getSums(bankAccounts, 'withdrawals'),
});
Output:
{
"deposits": [
401,
1100,
24456.57,
0,
118
],
"withdrawals": [
300.68,
0,
5900,
0,
100
]
}
UPDATE 1: Based on request to use only for loops:
const bankAccounts = [ { id: 1, name: "Susan", balance: 100.32, deposits: [150, 30, 221], withdrawals: [110, 70.68, 120], }, { id: 2, name: "Morgan", balance: 1100.0, deposits: [1100] }, { id: 3, name: "Joshua", balance: 18456.57, deposits: [4000, 5000, 6000, 9200, 256.57], withdrawals: [1500, 1400, 1500, 1500], }, { id: 4, name: "Candy", balance: 0.0 }, { id: 5, name: "Phil", balance: 18, deposits: [100, 18], withdrawals: [100] }, ];
function getAllWithdrawals(bankAccounts) {
let result = [];
for (let obj of bankAccounts) {
let sum = 0;
if(obj.withdrawals) {
for (num of obj.withdrawals) {
sum += num;
}
}
result.push(sum);
}
return result;
}
console.log(getAllWithdrawals(bankAccounts));
Not sure if I understood your question, but if u have to sum ALL of the withdrawals you should do it in this way:
const bankAccounts = [
{
id: 1,
name: "Susan",
balance: 100.32,
deposits: [150, 30, 221],
withdrawals: [110, 70.68, 120],
},
{ id: 2, name: "Morgan", balance: 1100.0, deposits: [1100] },
{
id: 3,
name: "Joshua",
balance: 18456.57,
deposits: [4000, 5000, 6000, 9200, 256.57],
withdrawals: [1500, 1400, 1500, 1500],
},
{ id: 4, name: "Candy", balance: 0.0 },
{ id: 5, name: "Phil", balance: 18, deposits: [100, 18], withdrawals: [100] },
];
function getAllWithdrawals(bankAccounts) {
let newArr = [];
for (let acc of bankAccounts) {
if (!!acc.withdrawals) {
acc.withdrawals.forEach(withdrawal => newArr.push(withdrawal))
}
}
return newArr.reduce((accumulator, currentValue) => accumulator + currentValue, 0);
}
console.log(getAllWithdrawals(bankAccounts))
Otherwise if you have to sum the withdrawals of the single object you have to use this code:
const bankAccounts = [
{
id: 1,
name: "Susan",
balance: 100.32,
deposits: [150, 30, 221],
withdrawals: [110, 70.68, 120],
},
{ id: 2, name: "Morgan", balance: 1100.0, deposits: [1100] },
{
id: 3,
name: "Joshua",
balance: 18456.57,
deposits: [4000, 5000, 6000, 9200, 256.57],
withdrawals: [1500, 1400, 1500, 1500],
},
{ id: 4, name: "Candy", balance: 0.0 },
{ id: 5, name: "Phil", balance: 18, deposits: [100, 18], withdrawals: [100] },
];
function getAllWithdrawals(bankAccounts) {
let newArr = [];
for (let acc of bankAccounts) {
if (!!acc.withdrawals) {
newArr.push(acc.withdrawals.reduce((accumulator, currentValue) => accumulator + currentValue, 0))
}
}
return newArr;
}
console.log(getAllWithdrawals(bankAccounts))

How to sort first 10 ids in ascending order , then id = 11 - id = 20 in descending order followed by id = 21 to id = 30 in ascending order and so on

I am making a board game using react. I am using an array of objects in the form
[
{ id : 1, tile : number, name : string},
{ id : 2, tile : number, name : string},
{ id : 3, tile : number, name : string},
{ id : 4, tile : number, name : string},
{ id : 5, tile : number, name : string},
{ id : 6, tile : number, name : string},
{ id : 7, tile : number, name : string},
{ id : 8, tile : number, name : string},
{ id : 9, tile : number, name : string},
{ id : 10, tile : number, name : string},
{ id : 11, tile : number, name : string},
.
.
.
{ id : 100, tile : number, name : string},
]
I want to sort the id 1 -10 as ascending, 11 - 20 as descending, 21 - 30 as ascending 31 to 40 as desc, and so on.
i have tried multiple methods
splitting the entire array (having 100 objects) into groups of 10 and then applying sort (asc/desc) to them and finally using the concat() to get the final sorted array
using splice(0, 10).sort((a, b) => a.id > b.id ? 1 : -1).map(value => value.id);
//for first 10 ids
spice(11, 20).sort((a, b) => a.id > b.id ? 1 : -1).reverse().map(value => value.id);
//for 11 - 20 ids and following the same pattern till 91 - 100.
putting conditions inside the sort itself (based on the units and tens place digits of the individual ids..)
for eg :
const Tiles = [
{}, {}, {}, ..... {}, //100 objects with unique ids
]
const sortTiles = Tiles.sort((a : any, b : any) =>
parseInt(String(a.id).charAt(0) % 2 == 0)? 1 : -1); //for sorting 20s, 40s, 60s, 80s digits as ascending...
but i want an optimal way of sorting the numbers as per the scheme I mentioned above.
1 - 10 asc - left to right
11 - 20 desc - left to right
21 - 30 asc - left to right
31 - 40 desc - left to right
... and so on.
here is my code - please suggest better solutions
const Tiles = [
{
id: 1,
tilenumber: 1,
name: "start"
},
{
id: 2,
tilenumber: 2,
name: "two"
},
{
id: 3,
tilenumber: 3,
name: "three"
},
{
id: 4,
tilenumber: 4,
name: "four"
},
{
id: 5,
tilenumber: 5,
name: "five"
},
{
id: 6,
tilenumber: 6,
name: "six"
},
{
id: 7,
tilenumber: 7,
name: "seven"
},
{
id: 8,
tilenumber: 8,
name: "eight"
},
{
id: 9,
tilenumber: 9,
name: "nine"
},
{
id: 10,
tilenumber: 10,
name: "ten"
},
{
id: 11,
tilenumber: 11,
name: "eleven"
},
{
id: 12,
tilenumber: 12,
name: "tweleve"
},
{
id: 13,
tilenumber: 13,
name: "thirteen"
},
{
id: 14,
tilenumber: 14,
name: "fourten"
},
{
id: 15,
tilenumber: 15,
name: "fifteen"
},
{
id: 16,
tilenumber: 16,
name: "sixteen"
},
{
id: 17,
tilenumber: 17,
name: "seventeen"
},
{
id: 18,
tilenumber: 18,
name: "eighteen"
},
{
id: 19,
tilenumber: 19,
name: "nineteen"
},
{
id: 20,
tilenumber: 20,
name: "twenty"
},
{
id: 21,
tilenumber: 21,
name: "twentyone"
},
{
id: 22,
tilenumber: 22,
name: "twentytwo"
},
{
id: 23,
tilenumber: 23,
name: "twentythree"
},
{
id: 24,
tilenumber: 24,
name: "twentyfour"
},
{
id: 25,
tilenumber: 25,
name: "twentyfive"
},
{
id: 26,
tilenumber: 26,
name: "twentysix"
},
{
id: 27,
tilenumber: 27,
name: "twentyseven"
},
{
id: 28,
tilenumber: 28,
name: "twentyeight"
},
{
id: 29,
tilenumber: 29,
name: "twentynine"
},
{
id: 30,
tilenumber: 30,
name: "thirty"
},
{
id: 31,
tilenumber: 31,
name: "thirtyone"
},
{
id: 32,
tilenumber: 32,
name: "thirtytwo"
},
{
id: 33,
tilenumber: 33,
name: "thirtythree"
},
{
id: 34,
tilenumber: 34,
name: "thirtyfour"
},
{
id: 35,
tilenumber: 35,
name: "thirtyfive"
},
{
id: 36,
tilenumber: 36,
name: "thirtysix"
},
{
id: 37,
tilenumber: 37,
name: "thirtyseven"
},
{
id: 38,
tilenumber: 38,
name: "thirtyeight"
},
{
id: 39,
tilenumber: 39,
name: "thirtynine"
},
{
id: 40,
tilenumber: 40,
name: "fourty"
},
{
id: 41,
tilenumber: 41,
name: "fourtyOne"
},
{
id: 42,
tilenumber: 42,
name: "fourtyTwo"
},
{
id: 43,
tilenumber: 43,
name: "fourtyThree"
},
{
id: 44,
tilenumber: 44,
name: "fourtyFour"
},
{
id: 45,
tilenumber: 45,
name: "fourtyFive"
},
{
id: 46,
tilenumber: 46,
name: "fourtySix"
},
{
id: 47,
tilenumber: 47,
name: "fourtySeven"
},
{
id: 48,
tilenumber: 48,
name: "fourtyEight"
},
{
id: 49,
tilenumber: 49,
name: "fourtyNine"
},
{
id: 50,
tilenumber: 50,
name: "fifty"
},
{
id: 51,
tilenumber: 51,
name: "fiftyOne"
},
{
id: 52,
tilenumber: 52,
name: "fiftyTwo"
},
{
id: 53,
tilenumber: 53,
name: "fiftyThree"
},
{
id: 54,
tilenumber: 54,
name: "fiftyFour"
},
{
id: 55,
tilenumber: 55,
name: "fiftyFive"
},
{
id: 56,
tilenumber: 56,
name: "fiftySix"
},
{
id: 57,
tilenumber: 57,
name: "fiftySeven"
},
{
id: 58,
tilenumber: 58,
name: "fiftyEight"
},
{
id: 59,
tilenumber: 59,
name: "fiftyNine"
},
{
id: 60,
tilenumber: 60,
name: "Sixty"
},
{
id: 61,
tilenumber: 61,
name: "sixtyOne"
},
{
id: 62,
tilenumber: 62,
name: "sixtyTwo"
},
{
id: 63,
tilenumber: 63,
name: "sixtyThree"
},
{
id: 64,
tilenumber: 64,
name: "sixtyFour"
},
{
id: 65,
tilenumber: 65,
name: "sixtyFive"
},
{
id: 66,
tilenumber: 66,
name: "sixtySix"
},
{
id: 67,
tilenumber: 67,
name: "sixtySeven"
},
{
id: 68,
tilenumber: 68,
name: "sixtyEight"
},
{
id: 69,
tilenumber: 69,
name: "sixtyNine"
},
{
id: 70,
tilenumber: 70,
name: "Seventy"
}, {
id: 71,
tilenumber: 71,
name: "seventyOne"
},
{
id: 72,
tilenumber: 72,
name: "seventyTwo"
},
{
id: 73,
tilenumber: 73,
name: "seventyThree"
},
{
id: 74,
tilenumber: 74,
name: "seventyFour"
},
{
id: 75,
tilenumber: 75,
name: "seventyFive"
},
{
id: 76,
tilenumber: 76,
name: "seventySix"
},
{
id: 77,
tilenumber: 77,
name: "seventySeven"
},
{
id: 78,
tilenumber: 78,
name: "seventyEight"
},
{
id: 79,
tilenumber: 79,
name: "seventyNine"
},
{
id: 80,
tilenumber: 80,
name: "Eighty"
}, {
id: 81,
tilenumber: 81,
name: "eightyOne"
},
{
id: 82,
tilenumber: 82,
name: "eightyTwo"
},
{
id: 83,
tilenumber: 83,
name: "eightyThree"
},
{
id: 84,
tilenumber: 84,
name: "eightyFour"
},
{
id: 85,
tilenumber: 85,
name: "eightyFive"
},
{
id: 86,
tilenumber: 86,
name: "eightSix"
},
{
id: 87,
tilenumber: 87,
name: "eightySeven"
},
{
id: 88,
tilenumber: 88,
name: "eightyEight"
},
{
id: 89,
tilenumber: 89,
name: "eightyNine"
},
{
id: 90,
tilenumber: 90,
name: "Ninety"
}, {
id: 91,
tilenumber: 91,
name: "ninetyOne"
},
{
id: 92,
tilenumber: 92,
name: "ninetyTwo"
},
{
id: 93,
tilenumber: 93,
name: "ninetyThree"
},
{
id: 94,
tilenumber: 94,
name: "ninetyFour"
},
{
id: 95,
tilenumber: 95,
name: "ninetyFive"
},
{
id: 96,
tilenumber: 96,
name: "ninetySix"
},
{
id: 97,
tilenumber: 97,
name: "ninetySeven"
},
{
id: 98,
tilenumber: 98,
name: "ninetyEight"
},
{
id: 99,
tilenumber: 99,
name: "ninetyNine"
},
{
id: 100,
tilenumber: 100,
name: "Hundread"
}
];
/*var newSetTiles = Tiles.sort((a : any , b : any) =>
parseInt(String(a.id).charAt(0))%2 == 0 || parseInt(String(a.id).charAt(1)) == 0 ? 1 : -1);
console.log(newSetTiles, 'sorted'); */
const tileSetA = Tiles.slice(0, 10).sort((a : any, b : any) => a.id > b.id ? 1 : -1);
const tileSetB = Tiles.slice(11, 20).sort((a : any, b : any) => a.id > b.id ? 1 : -1).reverse();
const tileSetC = Tiles.slice(21, 30).sort((a : any, b : any) => a.id > b.id ? 1 : -1);
const concatSet = tileSetA.concat(tileSetB);
const concatSet_ = concatSet.concat(tileSetB);
console.log(concatSet_);
export default concatSet_;
How about this:
Create a loop for each slice, if even index just append it to new array, if odd reverse order then append it to new array.
const Tiles = [{
id: 1,
tilenumber: 1,
name: "start"
},
{
id: 2,
tilenumber: 2,
name: "two"
},
{
id: 3,
tilenumber: 3,
name: "three"
},
{
id: 4,
tilenumber: 4,
name: "four"
},
{
id: 5,
tilenumber: 5,
name: "five"
},
{
id: 6,
tilenumber: 6,
name: "six"
},
{
id: 7,
tilenumber: 7,
name: "seven"
},
{
id: 8,
tilenumber: 8,
name: "eight"
},
{
id: 9,
tilenumber: 9,
name: "nine"
},
{
id: 10,
tilenumber: 10,
name: "ten"
},
{
id: 11,
tilenumber: 11,
name: "eleven"
},
{
id: 12,
tilenumber: 12,
name: "tweleve"
},
{
id: 13,
tilenumber: 13,
name: "thirteen"
},
{
id: 14,
tilenumber: 14,
name: "fourten"
},
{
id: 15,
tilenumber: 15,
name: "fifteen"
},
{
id: 16,
tilenumber: 16,
name: "sixteen"
},
{
id: 17,
tilenumber: 17,
name: "seventeen"
},
{
id: 18,
tilenumber: 18,
name: "eighteen"
},
{
id: 19,
tilenumber: 19,
name: "nineteen"
},
{
id: 20,
tilenumber: 20,
name: "twenty"
},
{
id: 21,
tilenumber: 21,
name: "twentyone"
},
{
id: 22,
tilenumber: 22,
name: "twentytwo"
},
{
id: 23,
tilenumber: 23,
name: "twentythree"
},
{
id: 24,
tilenumber: 24,
name: "twentyfour"
},
{
id: 25,
tilenumber: 25,
name: "twentyfive"
},
{
id: 26,
tilenumber: 26,
name: "twentysix"
},
{
id: 27,
tilenumber: 27,
name: "twentyseven"
},
{
id: 28,
tilenumber: 28,
name: "twentyeight"
},
{
id: 29,
tilenumber: 29,
name: "twentynine"
},
{
id: 30,
tilenumber: 30,
name: "thirty"
},
{
id: 31,
tilenumber: 31,
name: "thirtyone"
},
{
id: 32,
tilenumber: 32,
name: "thirtytwo"
},
{
id: 33,
tilenumber: 33,
name: "thirtythree"
},
{
id: 34,
tilenumber: 34,
name: "thirtyfour"
},
{
id: 35,
tilenumber: 35,
name: "thirtyfive"
},
{
id: 36,
tilenumber: 36,
name: "thirtysix"
},
{
id: 37,
tilenumber: 37,
name: "thirtyseven"
},
{
id: 38,
tilenumber: 38,
name: "thirtyeight"
},
{
id: 39,
tilenumber: 39,
name: "thirtynine"
},
{
id: 40,
tilenumber: 40,
name: "fourty"
},
{
id: 41,
tilenumber: 41,
name: "fourtyOne"
},
{
id: 42,
tilenumber: 42,
name: "fourtyTwo"
},
{
id: 43,
tilenumber: 43,
name: "fourtyThree"
},
{
id: 44,
tilenumber: 44,
name: "fourtyFour"
},
{
id: 45,
tilenumber: 45,
name: "fourtyFive"
},
{
id: 46,
tilenumber: 46,
name: "fourtySix"
},
{
id: 47,
tilenumber: 47,
name: "fourtySeven"
},
{
id: 48,
tilenumber: 48,
name: "fourtyEight"
},
{
id: 49,
tilenumber: 49,
name: "fourtyNine"
},
{
id: 50,
tilenumber: 50,
name: "fifty"
},
{
id: 51,
tilenumber: 51,
name: "fiftyOne"
},
{
id: 52,
tilenumber: 52,
name: "fiftyTwo"
},
{
id: 53,
tilenumber: 53,
name: "fiftyThree"
},
{
id: 54,
tilenumber: 54,
name: "fiftyFour"
},
{
id: 55,
tilenumber: 55,
name: "fiftyFive"
},
{
id: 56,
tilenumber: 56,
name: "fiftySix"
},
{
id: 57,
tilenumber: 57,
name: "fiftySeven"
},
{
id: 58,
tilenumber: 58,
name: "fiftyEight"
},
{
id: 59,
tilenumber: 59,
name: "fiftyNine"
},
{
id: 60,
tilenumber: 60,
name: "Sixty"
},
{
id: 61,
tilenumber: 61,
name: "sixtyOne"
},
{
id: 62,
tilenumber: 62,
name: "sixtyTwo"
},
{
id: 63,
tilenumber: 63,
name: "sixtyThree"
},
{
id: 64,
tilenumber: 64,
name: "sixtyFour"
},
{
id: 65,
tilenumber: 65,
name: "sixtyFive"
},
{
id: 66,
tilenumber: 66,
name: "sixtySix"
},
{
id: 67,
tilenumber: 67,
name: "sixtySeven"
},
{
id: 68,
tilenumber: 68,
name: "sixtyEight"
},
{
id: 69,
tilenumber: 69,
name: "sixtyNine"
},
{
id: 70,
tilenumber: 70,
name: "Seventy"
}, {
id: 71,
tilenumber: 71,
name: "seventyOne"
},
{
id: 72,
tilenumber: 72,
name: "seventyTwo"
},
{
id: 73,
tilenumber: 73,
name: "seventyThree"
},
{
id: 74,
tilenumber: 74,
name: "seventyFour"
},
{
id: 75,
tilenumber: 75,
name: "seventyFive"
},
{
id: 76,
tilenumber: 76,
name: "seventySix"
},
{
id: 77,
tilenumber: 77,
name: "seventySeven"
},
{
id: 78,
tilenumber: 78,
name: "seventyEight"
},
{
id: 79,
tilenumber: 79,
name: "seventyNine"
},
{
id: 80,
tilenumber: 80,
name: "Eighty"
}, {
id: 81,
tilenumber: 81,
name: "eightyOne"
},
{
id: 82,
tilenumber: 82,
name: "eightyTwo"
},
{
id: 83,
tilenumber: 83,
name: "eightyThree"
},
{
id: 84,
tilenumber: 84,
name: "eightyFour"
},
{
id: 85,
tilenumber: 85,
name: "eightyFive"
},
{
id: 86,
tilenumber: 86,
name: "eightSix"
},
{
id: 87,
tilenumber: 87,
name: "eightySeven"
},
{
id: 88,
tilenumber: 88,
name: "eightyEight"
},
{
id: 89,
tilenumber: 89,
name: "eightyNine"
},
{
id: 90,
tilenumber: 90,
name: "Ninety"
}, {
id: 91,
tilenumber: 91,
name: "ninetyOne"
},
{
id: 92,
tilenumber: 92,
name: "ninetyTwo"
},
{
id: 93,
tilenumber: 93,
name: "ninetyThree"
},
{
id: 94,
tilenumber: 94,
name: "ninetyFour"
},
{
id: 95,
tilenumber: 95,
name: "ninetyFive"
},
{
id: 96,
tilenumber: 96,
name: "ninetySix"
},
{
id: 97,
tilenumber: 97,
name: "ninetySeven"
},
{
id: 98,
tilenumber: 98,
name: "ninetyEight"
},
{
id: 99,
tilenumber: 99,
name: "ninetyNine"
},
{
id: 100,
tilenumber: 100,
name: "Hundread"
}
];
// First make sure they are in order, this may not be needed if you know they start in order
Tiles.sort((a, b) => a.id - b.id);
let newArray = [];
const sections = Math.ceil(Tiles.length / 10)
for (let i = 0; i < sections; i++) {
const slice = Tiles.slice(i * 10, i * 10 + 10);
if (i % 2 === 1) {
slice.sort((a, b) => b.id - a.id);
}
newArray = newArray.concat(slice);
}
console.log(newArray);
Or if you prefer here is a one-line solution:
const newArray = Array.from({length: Math.ceil(Tiles.length / 10)}, () => Tiles.splice(0, 10)).map((chunk, i) => i % 2 === 0 ? chunk : chunk.sort((a, b) => b.id - a.id)).flat()
See methods:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/flat
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/from
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice
const Tiles = [{
id: 1,
tilenumber: 1,
name: "start"
},
{
id: 2,
tilenumber: 2,
name: "two"
},
{
id: 3,
tilenumber: 3,
name: "three"
},
{
id: 4,
tilenumber: 4,
name: "four"
},
{
id: 5,
tilenumber: 5,
name: "five"
},
{
id: 6,
tilenumber: 6,
name: "six"
},
{
id: 7,
tilenumber: 7,
name: "seven"
},
{
id: 8,
tilenumber: 8,
name: "eight"
},
{
id: 9,
tilenumber: 9,
name: "nine"
},
{
id: 10,
tilenumber: 10,
name: "ten"
},
{
id: 11,
tilenumber: 11,
name: "eleven"
},
{
id: 12,
tilenumber: 12,
name: "tweleve"
},
{
id: 13,
tilenumber: 13,
name: "thirteen"
},
{
id: 14,
tilenumber: 14,
name: "fourten"
},
{
id: 15,
tilenumber: 15,
name: "fifteen"
},
{
id: 16,
tilenumber: 16,
name: "sixteen"
},
{
id: 17,
tilenumber: 17,
name: "seventeen"
},
{
id: 18,
tilenumber: 18,
name: "eighteen"
},
{
id: 19,
tilenumber: 19,
name: "nineteen"
},
{
id: 20,
tilenumber: 20,
name: "twenty"
},
{
id: 21,
tilenumber: 21,
name: "twentyone"
},
{
id: 22,
tilenumber: 22,
name: "twentytwo"
},
{
id: 23,
tilenumber: 23,
name: "twentythree"
},
{
id: 24,
tilenumber: 24,
name: "twentyfour"
},
{
id: 25,
tilenumber: 25,
name: "twentyfive"
},
{
id: 26,
tilenumber: 26,
name: "twentysix"
},
{
id: 27,
tilenumber: 27,
name: "twentyseven"
},
{
id: 28,
tilenumber: 28,
name: "twentyeight"
},
{
id: 29,
tilenumber: 29,
name: "twentynine"
},
{
id: 30,
tilenumber: 30,
name: "thirty"
},
{
id: 31,
tilenumber: 31,
name: "thirtyone"
},
{
id: 32,
tilenumber: 32,
name: "thirtytwo"
},
{
id: 33,
tilenumber: 33,
name: "thirtythree"
},
{
id: 34,
tilenumber: 34,
name: "thirtyfour"
},
{
id: 35,
tilenumber: 35,
name: "thirtyfive"
},
{
id: 36,
tilenumber: 36,
name: "thirtysix"
},
{
id: 37,
tilenumber: 37,
name: "thirtyseven"
},
{
id: 38,
tilenumber: 38,
name: "thirtyeight"
},
{
id: 39,
tilenumber: 39,
name: "thirtynine"
},
{
id: 40,
tilenumber: 40,
name: "fourty"
},
{
id: 41,
tilenumber: 41,
name: "fourtyOne"
},
{
id: 42,
tilenumber: 42,
name: "fourtyTwo"
},
{
id: 43,
tilenumber: 43,
name: "fourtyThree"
},
{
id: 44,
tilenumber: 44,
name: "fourtyFour"
},
{
id: 45,
tilenumber: 45,
name: "fourtyFive"
},
{
id: 46,
tilenumber: 46,
name: "fourtySix"
},
{
id: 47,
tilenumber: 47,
name: "fourtySeven"
},
{
id: 48,
tilenumber: 48,
name: "fourtyEight"
},
{
id: 49,
tilenumber: 49,
name: "fourtyNine"
},
{
id: 50,
tilenumber: 50,
name: "fifty"
},
{
id: 51,
tilenumber: 51,
name: "fiftyOne"
},
{
id: 52,
tilenumber: 52,
name: "fiftyTwo"
},
{
id: 53,
tilenumber: 53,
name: "fiftyThree"
},
{
id: 54,
tilenumber: 54,
name: "fiftyFour"
},
{
id: 55,
tilenumber: 55,
name: "fiftyFive"
},
{
id: 56,
tilenumber: 56,
name: "fiftySix"
},
{
id: 57,
tilenumber: 57,
name: "fiftySeven"
},
{
id: 58,
tilenumber: 58,
name: "fiftyEight"
},
{
id: 59,
tilenumber: 59,
name: "fiftyNine"
},
{
id: 60,
tilenumber: 60,
name: "Sixty"
},
{
id: 61,
tilenumber: 61,
name: "sixtyOne"
},
{
id: 62,
tilenumber: 62,
name: "sixtyTwo"
},
{
id: 63,
tilenumber: 63,
name: "sixtyThree"
},
{
id: 64,
tilenumber: 64,
name: "sixtyFour"
},
{
id: 65,
tilenumber: 65,
name: "sixtyFive"
},
{
id: 66,
tilenumber: 66,
name: "sixtySix"
},
{
id: 67,
tilenumber: 67,
name: "sixtySeven"
},
{
id: 68,
tilenumber: 68,
name: "sixtyEight"
},
{
id: 69,
tilenumber: 69,
name: "sixtyNine"
},
{
id: 70,
tilenumber: 70,
name: "Seventy"
}, {
id: 71,
tilenumber: 71,
name: "seventyOne"
},
{
id: 72,
tilenumber: 72,
name: "seventyTwo"
},
{
id: 73,
tilenumber: 73,
name: "seventyThree"
},
{
id: 74,
tilenumber: 74,
name: "seventyFour"
},
{
id: 75,
tilenumber: 75,
name: "seventyFive"
},
{
id: 76,
tilenumber: 76,
name: "seventySix"
},
{
id: 77,
tilenumber: 77,
name: "seventySeven"
},
{
id: 78,
tilenumber: 78,
name: "seventyEight"
},
{
id: 79,
tilenumber: 79,
name: "seventyNine"
},
{
id: 80,
tilenumber: 80,
name: "Eighty"
}, {
id: 81,
tilenumber: 81,
name: "eightyOne"
},
{
id: 82,
tilenumber: 82,
name: "eightyTwo"
},
{
id: 83,
tilenumber: 83,
name: "eightyThree"
},
{
id: 84,
tilenumber: 84,
name: "eightyFour"
},
{
id: 85,
tilenumber: 85,
name: "eightyFive"
},
{
id: 86,
tilenumber: 86,
name: "eightSix"
},
{
id: 87,
tilenumber: 87,
name: "eightySeven"
},
{
id: 88,
tilenumber: 88,
name: "eightyEight"
},
{
id: 89,
tilenumber: 89,
name: "eightyNine"
},
{
id: 90,
tilenumber: 90,
name: "Ninety"
}, {
id: 91,
tilenumber: 91,
name: "ninetyOne"
},
{
id: 92,
tilenumber: 92,
name: "ninetyTwo"
},
{
id: 93,
tilenumber: 93,
name: "ninetyThree"
},
{
id: 94,
tilenumber: 94,
name: "ninetyFour"
},
{
id: 95,
tilenumber: 95,
name: "ninetyFive"
},
{
id: 96,
tilenumber: 96,
name: "ninetySix"
},
{
id: 97,
tilenumber: 97,
name: "ninetySeven"
},
{
id: 98,
tilenumber: 98,
name: "ninetyEight"
},
{
id: 99,
tilenumber: 99,
name: "ninetyNine"
},
{
id: 100,
tilenumber: 100,
name: "Hundread"
}
];
// First make sure they are in order, this may not be needed if you know they start in order
Tiles.sort((a, b) => a.id - b.id);
const newArray = Array.from({
length: Math.ceil(Tiles.length / 10)
}, () => Tiles.splice(0, 10)).map((chunk, i) => i % 2 === 0 ? chunk : chunk.sort((a, b) => b.id - a.id)).flat()
console.log(newArray);

How do I properly sort this array?

I've created a couple arrays. arrLocations holds a series of 2-digit country names, arrResults counts how many times each occurs and holds the country name with it's count as see here:
[
FR: 40, US: 1511, AU: 82,
CN: 151, IE: 170, SG: 108,
GB: 66, KR: 52, JP: 137,
IN: 45, BR: 68, SE: 39,
ZA: 19, NL: 19, BH: 19,
LU: 3, CA: 41, DE: 79,
ID: 1, HK: 1
]
My intention is to sort this array by ascending occurrence, I want this:
[
ID: 1, HK: 1, LU: 3,
BH: 19, NL: 19, ZA: 19,
....and so on........
]
However, no matter what way I implement sort, it does absolutely nothing. I even did a test sort on a dumby array and was able to sort it fine, but this array I cannot sort.
Here is what I have so far:
var geoip = require('geoip-lite')
const fs = require('fs')
const { Console } = require('console')
let data = fs.readFileSync('./ip_new.txt')
let iplocation = ""
let arrLocations = []
let arrResults = []
let arrIP = data.toString().split("\r\n")
for(let item of arrIP){
iplocation = geoip.lookup(item)
arrLocations.push(iplocation.country)
}
for(let item of arrLocations){
if (item in arrResults){
arrResults[item]++
}
else{
arrResults[item]=1
}
}
arrResults.sort()
console.log(arrResults)
OK, so first of all I'm assuming this
[
FR: 40, US: 1511, AU: 82,
CN: 151, IE: 170, SG: 108,
GB: 66, KR: 52, JP: 137,
IN: 45, BR: 68, SE: 39,
ZA: 19, NL: 19, BH: 19,
LU: 3, CA: 41, DE: 79,
ID: 1, HK: 1
]
Is actually this
[
{ FR: 40 }, { US: 1511 }, { AU: 82 },
{ CN: 151 }, { IE: 170 }, { SG: 108 },
{ GB: 66 }, { KR: 52 }, { JP: 137 },
{ IN: 45 }, { BR: 68 }, { SE: 39 },
{ ZA: 19 }, { NL: 19 }, { BH: 19 },
{ LU: 3 }, { CA: 41 }, { DE: 79 },
{ ID: 1 }, { HK: 1 }
]
If this is true, then sort method will not work on it's own. The following will do though:
const arrResults = [
{ FR: 40 }, { US: 1511 }, { AU: 82 },
{ CN: 151 }, { IE: 170 }, { SG: 108 },
{ GB: 66 }, { KR: 52 }, { JP: 137 },
{ IN: 45 }, { BR: 68 }, { SE: 39 },
{ ZA: 19 }, { NL: 19 }, { BH: 19 },
{ LU: 3 }, { CA: 41 }, { DE: 79 },
{ ID: 1 }, { HK: 1 }
];
arrResults.sort((a, b) => {
const countryCodeA = Object.keys(a)[0];
const countryCodeB = Object.keys(b)[0];
return a[countryCodeA] - b[countryCodeB];
});

How to select random object from JSON file in discord.js

I've done some searching around and I found some posts on here but my code doesn't want to work.
Basically I'm making a discord bot and I want to select an object from a JSON file at random.
This is my command:
const UserData = require('../data/users.js');
const monster = require('../data/monsters.json');
module.exports = {
name: 'battle',
aliases: ['fight'],
cooldown: 0,
description: 'User fights against a monster alone or in group',
execute(client, message, args) {
let enemy = monster[Math.floor(Math.random() * monster.length)]
UserData.findOne({
userID: message.author.id
}, (error, userdata) => {
if (error) console.log(error);
if (!userdata) {
return message.reply(`you don't have an account!`);
} else {
console.log(enemy);
return message.channel.send(`${enemy} spawned!`);
}
})
}
}
And this is my JSON file:
"1" : {
"name": "Blue Slime",
"hp": 20,
"atk": 12,
"def": 10,
"spatk": 3,
"spdef": 12,
"spd": 100,
"gold": 10,
"xp": 50,
"lvl": 1
},
"2": {
"name": "Red slime",
"hp": 20,
"atk": 12,
"def": 10,
"spatk": 3,
"spdef": 12,
"spd": 100,
"gold": 10,
"xp": 50,
"lvl": 1
},
"3": {
"name": "Green slime",
"hp": 20,
"atk": 12,
"def": 10,
"spatk": 3,
"spdef": 12,
"spd": 100,
"gold": 10,
"xp": 50,
"lvl": 1
}
}
If I want put the objects in the command manually and then randomly select them it works and if instead of "monster.length" I put a number then it also works but I still get undefined if it should be 3.
This way I also always get undefined in console log from monster.length.
What am I doing wrong?
Your monsters.json file contains an object and objects don't have lengths. You can however convert it to an array, using Object.values() that returns an array of the given object's own enumerable property values.
Check out the snippet below:
let monsters = {
1: {
name: 'Blue Slime',
hp: 20,
atk: 12,
def: 10,
spatk: 3,
spdef: 12,
spd: 100,
gold: 10,
xp: 50,
lvl: 1,
},
2: {
name: 'Red slime',
hp: 20,
atk: 12,
def: 10,
spatk: 3,
spdef: 12,
spd: 100,
gold: 10,
xp: 50,
lvl: 1,
},
3: {
name: 'Green slime',
hp: 20,
atk: 12,
def: 10,
spatk: 3,
spdef: 12,
spd: 100,
gold: 10,
xp: 50,
lvl: 1,
},
};
function randomObject(obj) {
let arr = Object.values(obj);
return arr[Math.floor(Math.random() * arr.length)];
}
let enemy = randomObject(monsters);
console.log(enemy);

How do I convert array to an array object and combine two arrays to a one array?

const absentStudentsId = [78, 15, 41, 30] // ======> [{stdId: 78, isPresent: false}, {stdId: 15, isPresent: false}, {stdId: 41, isPresent: false}, {stdId: 30, isPresent: false}]
const presentStudentsId = [80, 61] // ======> [{stdId: 80, isPresent: true}, {stdId: 61, isPresent: true}]
const students = [
{ stdId: 78, isPresent: false },
{ stdId: 15, isPresent: false },
{ stdId: 41, isPresent: false },
{ stdId: 30, isPresent: false },
{ stdId: 80, isPresent: true },
{ stdId: 61, isPresent: true },
]
I want to implement that logic as you see in the commented line.
You could take a closure over isPresent and map new objects.
const
buildObject = isPresent => stdId => ({ stdId, isPresent }),
absentStudentsId = [78, 15, 41, 30],
presentStudentsId = [80, 61],
students = [
...absentStudentsId.map(buildObject(false)),
...presentStudentsId.map(buildObject(true))
];
console.log(students);
.as-console-wrapper { max-height: 100% !important; top: 0; }
.map() -> loop over array elements and return a new item for eachitem with your desired computation.
...(Spread) -> spread operator which expands an array into individual elements.
let ans = [...(absentStudentsId.map(x => { return { stdId : x, present : false} })),...(presentStudentsId.map(x => {return { stdId : x, present : true} }))]
const absentStudentsId = [78, 15, 41, 30] // ======> [{stdId: 78, isPresent: false}, {stdId: 15, isPresent: false}, {stdId: 30, isPresent: false}]
const presentStudentsId = [80, 61] // ======> [{stdId: 80, isPresent: true}, {stdId: 61, isPresent: true}]
const transformStudents = (students, isPresent) => students.map(studentId => ({ stdId: studentId, isPresent}));
const allStudents = [...transformStudents(absentStudentsId, false), ...transformStudents(presentStudentsId, true)];
console.log(allStudents)
Yet another straightforward solution:
const absentStudentsId = [78, 15, 41, 30]
const presentStudentsId = [80, 61]
const students = []
absentStudentsId.forEach(id => students.push({stdID: id, isPresent: false}))
presentStudentsId.forEach(id => students.push({stdID: id, isPresent: true}))
console.log(students)
/*
[
{ stdID: 78, isPresent: false },
{ stdID: 15, isPresent: false },
{ stdID: 41, isPresent: false },
{ stdID: 30, isPresent: false },
{ stdID: 80, isPresent: true },
{ stdID: 61, isPresent: true }
]
*/

Categories