I have an array of objects returning from an API call which I need to sort into a specific format.
I'm trying to organise the destination_country_id alphabetically except for the first three and last items. For example, like so:
"Ireland"
"United Kingdom"
"United States"
...other countries, alphabetically...
"Everywhere Else"
I have considered using array.sort(), which I understand I can easily use to sort them alphabetically, but I've so far been unsuccessful in figuring out how I can achieve the desired output.
API Response
[
{
"destination_country_id":null,
"primary_cost":"9.50",
"region_id":null,
"destination_country_name":"Everywhere Else",
},
{
"destination_country_id":105,
"primary_cost":"8.00",
"region_id":null,
"destination_country_name":"United Kingdom",
},
{
"destination_country_id":209,
"primary_cost":"9.50",
"region_id":null,
"destination_country_name":"United States",
},
{
"destination_country_id":123,
"primary_cost":"5.00",
"region_id":null,
"destination_country_name":"Ireland",
},
{
"destination_country_id":185,
"primary_cost":"5.00",
"region_id":null,
"destination_country_name":"France",
},
{
"destination_country_id":145,
"primary_cost":"5.00",
"region_id":null,
"destination_country_name":"Spain",
}
]
Possibly not the most efficient method but it is ES3, doesn't require any libraries, and is fairly easy to understand. Also assuming you wanted to sort alphabetically on destination_country_name
Javascript
// where x is your array of objects
x.sort(function (a, b) {
// sorts everything alphabetically
return a.destination_country_name.localeCompare(b.destination_country_name);
}).sort(function (a, b) {
// moves only this to country to top
return +(!b.destination_country_name.localeCompare('United States'));
}).sort(function (a, b) {
// moves only this to country to top
return +(!b.destination_country_name.localeCompare('United Kingdom'));
}).sort(function (a, b) {
// moves only this to country to top
return +(!b.destination_country_name.localeCompare('Ireland'));
}).sort(function (a, b) {
// moves only this to country to bottom
return +(!a.destination_country_name.localeCompare('Everywhere Else'));
});
console.log(JSON.stringify(x, ['destination_country_name']));
Output
[{"destination_country_name":"Ireland"},
{"destination_country_name":"United Kingdom"},
{"destination_country_name":"United States"},
{"destination_country_name":"France"},
{"destination_country_name":"Spain"},
{"destination_country_name":"Everywhere Else"}]
On jsFiddle
We could even go a step further and use the above example to make a reusable function, like.
Javascript
function sorter(array, funcs, orders) {
funcs = funcs || {};
orders = orders || {};
array.sort(funcs.general);
if (Array.isArray(orders.top)) {
orders.top.slice().reverse().forEach(function(value) {
array.sort(funcs.top.bind(value));
});
}
if (Array.isArray(orders.bottom)) {
orders.bottom.forEach(function(value) {
array.sort(funcs.bottom.bind(value));
});
}
return array;
}
sorter(x, {
general: function (a, b) {
return a.destination_country_name.localeCompare(b.destination_country_name);
},
top: function (a, b) {
return +(!b.destination_country_name.localeCompare(this));
},
bottom: function (a, b) {
return +(!a.destination_country_name.localeCompare(this));
}
}, {
top: ['Ireland', 'United Kingdom', 'United States'],
bottom: ['Everywhere Else']
});
On jsFiddle
And now you can easily sort on different attributes by parsing in different compare functions, and define values that should be at the top or bottom.
I used ECMA5 methods but you could just as easily make it with ECMA3.
I think the most efficient way to sort your array is to first find where "Everywhere Else", the "UK", "Ireland", and the "US" are in your array, remove them, and then sort the rest of the array. This is simpler than it sounds
fiddle
var data = [
{"destination_country_name": "Everywhere Else"},
{"destination_country_name": "United Kingdom"},
{"destination_country_name": "United States"},
{"destination_country_name": "Ireland"},
{"destination_country_name": "France"},
{"destination_country_name": "Spain"} ];
//removed the other elements just to make the example cleaner
var keep = ["Everywhere Else", "Ireland", "United Kingdom", "United States"];
//keep is the elements you want in the front; order them exactly at you want them ordered
var top = [];
//this is our holder array to hold the objects for the strings in keep
for (var i = 0; i < keep.length; i++) {
var index = function () {
for (var j = 0; j < data.length; j++){ //loop through data
if (data[j].destination_country_name == keep[i])
return data[j]; //return the object if it's name matches the one in keep
}
}
if (index > -1){ //if the object is in the array (index != -1)
top.push(data[index]); //push the object to our holder array
data.splice(index, 1); //splice the object out of the original array
}
}
//after this loop, those other objects will have been removed
//sort the rest of that array of objects
data.sort(function (a, b) { //use a callback function to specify which parts of
//the object need to be sorted
//basic sorting/compare algorithm (-1, 0, or 1)
if (a.destination_country_name > b.destination_country_name)
return 1; //if greater
if (a.destination_country_name < b.destination_country_name)
return -1; //if lesser
return 0; //otherwise
})
var sorted = top.concat(data), //combine data to the holder array and assign to sorted
extra = sorted.shift(); //grab the first element ("Everywhere Else") and remove it
sorted.push(extra); //add that element to the end of the array
console.log(sorted);
Alternatively, if you know those four places (EE, UK, US, and Ireland) will always be the first 4 elements in your array, you can do the following:
var data = [
{"destination_country_name": "Everywhere Else"},
{"destination_country_name": "United Kingdom"},
{"destination_country_name": "United States"},
{"destination_country_name": "Ireland"},
{"destination_country_name": "France"},
{"destination_country_name": "Spain"} ];
var top = data.slice(0,4);
data.sort(function (a, b) {
if (a.destination_country_name > b.destination_country_name)
return 1;
if (a.destination_country_name < b.destination_country_name)
return -1;
return 0;
})
var sorted = top.concat(data),
extra = sorted.shift();
sorted = sorted.push(extra); //put "Everywhere Else" at the end of the array
Note how this is much more efficient (and much simpler!) because you don't need to locate those four elements.
You can give every object a 'sort-order' property. Specify the known first 3 and the last, and give all the others the same value, greater than the first three and less than the last. Then sort the array- first by sort-order, and then alphabetically;
var arr= [{ "destination_country_id": null, "primary_cost": "9.50",
"region_id": null, "destination_country_name": "Everywhere Else",
},{ "destination_country_id": 105, "primary_cost": "8.00",
"region_id": null, "destination_country_name": "United Kingdom",
},{ "destination_country_id": 209, "primary_cost": "9.50",
"region_id": null, "destination_country_name": "United States",
},{ "destination_country_id": 123, "primary_cost": "5.00",
"region_id": null, "destination_country_name": "Ireland", },{
"destination_country_id": 185, "primary_cost": "5.00",
"region_id": null, "destination_country_name": "France", },{
"destination_country_id": 145, "primary_cost": "5.00",
"region_id": null, "destination_country_name": "Spain", }]
var s= "destination_country_name",
order= ["Ireland", "United Kingdom",
"United States", "Everywhere Else"];
arr.forEach(function(itm){
var i= order.indexOf(itm[s]);
if(i!= -1) itm.sort_order= i== 3? 1e50: i;
else itm.sort_order= 10;
});
arr.sort(function(a, b){
var d= a.sort_order- b.sort_order;
if(d===0){
if(a[s]=== b[s]) return 0;
return a[s]>b[s]? 1: -1;
}
return d;
});
JSON.stringify(arr)
/* returned value: (String)[{
"destination_country_id": 123, "primary_cost": "5.00", "region_id": null,
"destination_country_name": "Ireland", "sort_order": 0
},{
"destination_country_id": 105, "primary_cost": "8.00", "region_id": null,
"destination_country_name": "United Kingdom", "sort_order": 1
},{
"destination_country_id": 209, "primary_cost": "9.50", "region_id": null,
"destination_country_name": "United States", "sort_order": 2
},{
"destination_country_id": 185, "primary_cost": "5.00", "region_id": null,
"destination_country_name": "France", "sort_order": 10
},{
"destination_country_id": 145, "primary_cost": "5.00", "region_id": null,
"destination_country_name": "Spain", "sort_order": 10
},{
"destination_country_id": null, "primary_cost": "9.50", "region_id": null,
"destination_country_name": "Everywhere Else", "sort_order": 1e+50
}
]
*/
If your provided array is called list, you can sort it as you want using the following call:
list.sort(function (item1, item2) {
if (item1.destination_country_name < item2.destination_country_name) {
return -1;
}
return 1;
});
you can use underscore sortBy method:
a=[{obj:'first3'},{obj:'first2'},{obj:'first1'},{obj:'z'},{obj:'m'},{obj:'c'},{obj:'end3'},{obj:'end2'},{obj:'end1'}]
a=_.sortBy(a,function (t,i){if (i<=2) return String.fromCharCode(0);if(i>=a.length-3) return String.fromCharCode(255);return t.obj })
console.log(JSON.stringify(a))
[{"obj":"first3"},{"obj":"first2"},{"obj":"first1"},{"obj":"c"},{"obj":"m"},{"obj":"z"},{"obj":"end3"},{"obj":"end2"},{"obj":"end1"}]
http://jsfiddle.net/43Q8h/
Related
I couldn't find the answer for this on Stack Overflow.
I have a function called quickSort:
function quickSort(array, prop) {
if (array.length <= 1) return array;
const pivot = array[0]; // I've tried array[0][prop] but it doesn't work
const left = [];
const right = [];
for (let i = 1; i < array.length; i++) {
if (array[i][prop] < pivot) {
left.push(array[i]);
} else {
right.push(array[i]);
}
}
return [...quickSort(left), pivot, ...quickSort(right)];
}
console.log(quickSort(data, 'motor'));
And I want sort this array of objects by motor:
let data = [
{
"color": "A",
"door": 1,
"wheel": 3,
"year": 1963,
"brand": "GMC",
"sold": false,
"owner": "Chalmers Boobyer",
"motor": 2.6,
"assembled": "20/08/2021"
},
{
"color": "B",
"door": 2,
"wheel": 2,
"year": 1980,
"brand": "Ford",
"sold": false,
"owner": "Angelia Cromett",
"motor": 2.5,
"assembled": "02/05/2021"
},
{
"color": "C",
"door": 3,
"wheel": 1,
"year": 1999,
"brand": "Audi",
"sold": false,
"owner": "Barth Pickring",
"motor": 2.0,
"assembled": "15/02/2021"
},
{
"color": "D",
"door": 4,
"wheel": 1,
"year": 2008,
"brand": "Hyundai",
"sold": true,
"owner": "Aurore Soaper",
"motor": 1.2,
"assembled": "02/01/2019"
}
];
Can someone explain how I can make array[0][prop] work?
I suggest reading How to Debug Small Programs. Adding a couple of strategic console.log statements before the comparison and at the start of the function to display the parameters is enough to show the problems. I did it for you this time, but you'll need to be able to debug your own programs if you want to make progress as a programmer.
A couple issues:
Your recursive calls quickSort(left) and quickSort(right) are missing the second parameter prop.
array[i][prop] < pivot is wrong if pivot is defined as array[0] because it compares different types. That should be const pivot = array[0][prop] as you attempted, but then you'd have to change your returned array to be
[...quickSort(left, prop), array[0], ...quickSort(right, prop)];
Here are the fixes applied:
const quickSort = (array, prop) => {
if (array.length <= 1) return array;
// warning: bad pivot
const pivot = array[0][prop];
const left = []; // warning: allocations
const right = [];
for (let i = 1; i < array.length; i++) {
if (array[i][prop] < pivot) {
left.push(array[i]);
}
else {
right.push(array[i]);
}
}
return [
...quickSort(left, prop),
array[0],
...quickSort(right, prop)
]; // warning: copies
};
const data = [
{
color: "A",
door: 1,
wheel: 3,
year: 1963,
brand: "GMC",
sold: false,
owner: "Chalmers Boobyer",
motor: 2.6,
assembled: "20/08/2021",
},
{
color: "B",
door: 2,
wheel: 2,
year: 1980,
brand: "Ford",
sold: false,
owner: "Angelia Cromett",
motor: 2.5,
assembled: "02/05/2021",
},
{
color: "C",
door: 3,
wheel: 1,
year: 1999,
brand: "Audi",
sold: false,
owner: "Barth Pickring",
motor: 2.0,
assembled: "15/02/2021",
},
{
color: "D",
door: 4,
wheel: 1,
year: 2008,
brand: "Hyundai",
sold: true,
owner: "Aurore Soaper",
motor: 1.2,
assembled: "02/01/2019",
},
];
console.log(quickSort(data, "motor"));
After the bug fixes, the sort still has issues:
Recursive sorts shouldn't be allocating memory and copying arrays. Use indices to determine the recursive subarrays and swaps to move elements into the correct subarrays. This makes the code harder to write and read, but provides significant performance improvements.
Choosing the pivot as 0 means you'll hit quadratic complexity and risk blowing the call stack on already-sorted data. Research and choose a better pivot-selection method.
Specifying prop is pretty limited. Better to provide a callback similar to the built-in sort, so you can sort any objects rather than just a top-level prop.
I have an array of objects that all have a phase key and I would like to only return the ones that match a specific phase value and then map several other key/values into the eventual return. Here's what I have so far:
phaseToBlocks (toggle, phase) {
this.phaseBlocks = this.$store.state.addresses.salesRepPhases
return this.phaseBlocks
.filter(fiber_phase === phase)
// .map(({id, phase, name, min_number, max_number}) => ({id: id, phase: fiber_phase, name: name, min_number: min_number, max_number: max_number}))
}
This is currently not filtering any out and returning the original array of objects. Here is a snippet of the array of objects:
[ { "fiber_phase": "101", "parsed_hash": "1bc7fb114ee10d7cb9cea10693d238b5", "min_number": 400, "max_number": 499, "sales_rep": "164", "id": "abd90d6b-28a8-2be6-d6c1-abd9007aef38", "name": "48TH ST E", "block_minimum": 400, "block_maximum": 498 }, { "fiber_phase": "101", "parsed_hash": "1bc7fb114ee10d7cb9cea10693d238b5", "min_number": 400, "max_number": 499, "sales_rep": "164", "id": "abd90d6b-28a8-2be6-d6c1-abd9007aef38", "name": "48TH ST E", "block_minimum": 401, "block_maximum": 499 }, { "fiber_phase": "103", "parsed_hash": "1e002ef82be950696f9053dc77b621cf", "min_number": 4700, "max_number": 4799, "sales_rep": "164", "id": "a1d58c9c-6ba7-ebc6-8a74-a1d5806e0bcf", "name": "11TH AVE S", "block_minimum": 4700, "block_maximum": 4798 }]
filter() takes a callback function that checks the condition and does the filtering:
return this.phaseBlocks
.filter(item => item.phase === phase);
If it's not clearer for you how .filter works, see this:
this.phaseBlocks.filter((phaseBlock) => {
return phaseBlock.fiber_phase === phase;
});
filter iterates through the array, and (phaseBlock) is the element of the array that is currently iterated.
Next, if the item is satisfying a condition (in this case its fiber_phase property is equal to phase) push that item to a new array created by filter.
For more, check the docs: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter
I want to iterate through this object by creating a function country(state,foods)
if the state and foods exists in the object,it should return me the state name and foods array of that state.First i tried iterating only state by passing argument state in the function using for in still i didn't get the state name and i don't know what should i do to get foods array.
var india = [
{
"state": "karnataka",
"capital": "Bengaluru",
"foods": ["Mysore masala", "Uthhappa", "Bisi Bele Bhaat"]
},
{
"state": "Maharashtra",
"capital": "Mumbai",
"foods": ["vada pav", "puranpoli", "Missal pav"]
},
{
"state": "Tamil nadu",
"capital": "Chennai",
"foods": ["Medu vada", "aapam", "idli sambhar"]
},
{
"state": "Rajasthan",
"capital": "Jaipur",
"foods": ["Ras malai", "Kadka", "Gujia"]
}
];
This is a poor data structure for your use case, so if you expect to need to search this data often, you might consider having state names as properties on an object for O(1) lookup rather than O(n) approach of iterating this array. That being said, this existing structure can be searched in this case using Array.find().
var result = india.find( item => (item.state === this) , searchState);
console.log(result.foods);
for (var i in india)
{
alert(india[i].state);
// do something else with india[i]
}
Or since india is an array:
for (var i = 0; i < india.length; ++i)
{
// same thing
}
When searching if a specific number or string exists in an array you can use Array.indexOf(), example:
if (india[i].foods.indexOf('Kadka') >= 0)
{
alert(india[i].state + " has food Kadka");
}
A function StateHasFood(state, food) could be something like that:
function StateHasFood(state, food)
{
for (var i in india)
if (india[i].state == state)
return india[i].foods.indexOf(food) >= 0;
return false;
}
Of course you can also return the object relative to the state containing its properties, including it's name and full list of foods like you seem to want:
function StateHasFood(state, food)
{
for (var i in india)
if (india[i].state == state)
if (india[i].foods.indexOf(food) >= 0)
return india[i];
return false;
}
Since you just told me to write a function to check if state and capital are present, and that is true then return the capital. I have wrote this for you. Hope it helps :)
var india = [
{
"state": "karnataka",
"capital": "Bengaluru",
"foods": ["Mysore masala", "Uthhappa", "Bisi Bele Bhaat"]
},
{
"state": "Maharashtra",
"capital": "Mumbai",
"foods": ["vada pav", "puranpoli", "Missal pav"]
},
{
"state": "Tamil nadu",
"capital": "Chennai",
"foods": ["Medu vada", "aapam", "idli sambhar"]
},
{
"state": "Rajasthan",
"capital": "Jaipur",
"foods": ["Ras malai", "Kadka", "Gujia"]
}
];
function country(someState , someCapital){
for (var i in india)
{
if(india[i].state === someState && india[i].capital === someCapital){
return india[i].capital;
}
}
}
document.write(country("Tamil nadu", "Chennai"));
From what you've added in the comments, it seems what you really want is a function getPropForState(state, prop) that will return the value of the specified property associated with the specified state. That is, getPropForState("Rajasthan", "foods") would return an array of foods, and getPropForState("Rajasthan", "capital") would return "Jaipur".
Assuming that is the case, perhaps something like the following:
// same array as in question, but with line breaks removed
// so that it doesn't clutter up my answer
var india = [{"state":"karnataka","capital":"Bengaluru","foods":["Mysore masala","Uthhappa","Bisi Bele Bhaat"]},{"state":"Maharashtra","capital":"Mumbai","foods":["vada pav","puranpoli","Missal pav"]},{"state":"Tamil nadu","capital":"Chennai","foods":["Medu vada","aapam","idli sambhar"]},{"state":"Rajasthan","capital":"Jaipur","foods":["Ras malai","Kadka","Gujia"]}];
function getPropForState(state, prop) {
var item = india.find(v => v.state === state);
if (item)
return item[prop];
}
console.log(getPropForState("Rajasthan", "foods")); // returns ["Ras malai","Kadka","Gujia"]
console.log(getPropForState("Rajasthan", "capital")); // returns "Jaipur"
console.log(getPropForState("Maharashtra", "capital")); // returns "Mumbai"
console.log(getPropForState("Maharashtra", "missing")); // returns undefined
console.log(getPropForState("Queensland", "foods")); // returns undefined
Note that if either the state or the specified other property do not exist then the function will return undefined.
Try forEach() method to iterate and Object.keys to get the key:value pairs. Don't completely understand OP's objective so I'll add objArrKey(). This function takes the array and a specific key and return all values associated with said key.
SNIPPET
var India = [{
"state": "karnataka",
"capital": "Bengaluru",
"foods": [
"Mysoremasala",
"Uthhappa",
"BisiBeleBhaat"
]
}, {
"state": "Maharashtra",
"capital": "Mumbai",
"foods": [
"vadapav",
"puranpoli",
"Missalpav"
]
}, {
"state": "Tamilnadu",
"capital": "Chennai",
"foods": [
"Meduvada",
"aapam",
"idlisambhar"
]
}, {
"state": "Rajasthan",
"capital": "Jaipur",
"foods": [
"Rasmalai",
"Kadka",
"Gujia"
]
}]
India.forEach(function(item) {
Object.keys(item).forEach(function(key) {
console.log("key:" + key + " value:" + item[key]);
});
});
function objArrKey(arr, key) {
return arr.map(function(item) {
return item[key] || null;
});
}
console.log(objArrKey(India, ['state']));
console.log(objArrKey(India, ['capital']));
console.log(objArrKey(India, ['foods']));
Basically, I have an array with objects and they would need to be grouped together. It is kinda hard to explain, but it might be easier if I just gave you guys an example.
Result data
[
{
"Category": "Préparé",
"Sandwich": "Martino",
"Ingredient": "Ansjovis",
"Price": 3.1
},
{
"Category": "Préparé",
"Sandwich": "Martino",
"Ingredient": "Tabasco",
"Price": 3.1
},
{
"Category": "Veggie",
"Sandwich": "Gezond",
"Ingredient": "Tomaat",
"Price": 2.5
},
{
"Category": "Veggie",
"Sandwich": "Gezond",
"Ingredient": "Kaas",
"Price": 2.5
}
];
This is a basic example of what my array looks like. I cannot change this structure, it is how our API provides the data.
What I actually need is this structure:
[
{
"CategoryName": "Prépare",
"Sandwiches": [
{
"SandwichName": "Martino",
"Price": 3.1,
"Ingredients": ["Ansjovis", "Tabasco"]
}
]
},
{
"CategoryName": "Veggie",
"Sandwiches": [
{
"SandwichName": "Gezond",
"Price": 2.5,
"Ingredients": ["Tomaat", "Kaas"]
}
]
}
]
I have tried some stuff with Underscore and _.groupBy, _.sortBy, _.countBy
But alas, nothing I have tried actually works. Is this even possible with Underscore (or some other library)?
Also on a sidenote, this example might have some JSON structure mistakes, because I wrote it myself. The data provided by the API has a correct format.
The example only has 2 sandwiches, but in real-time, I'll be retrieving multiple categories with each 20 sandwiches and so on. This is just a minified example, but it provides an idea of what I need.
try this in simple js
var map = {};
results.forEach( function(obj){
map[ obj.CategoryName ] = map[ obj.CategoryName ] || [];
map[ obj.CategoryName ].push( obj );
});
var output = Object.keys(map).map( function(key){
var arr = [];
map[key].forEach(function(obj){
arr.push( {
"SandwichName": obj.SandwichName,
"Price": obj.Price,
"Ingredients": obj.Ingredients
});
});
return { "CategoryName" : key , "Sandwiches" : arr };
});
The following piece of code would do the trick for you:
var data = [...]; // this is your json-data
var result = _.map(_.uniq(_.pluck(data, 'Category')), function(category) {
var sandwiches = _.uniq(_.pluck(_.where(data, { Category: category }), 'Sandwich'));
return {
CategoryName: category,
Sandwiches: _.map(sandwiches, function(sandwich) {
return {
SandwitchName: sandwich,
Price: _.findWhere(data, { Category: category, Sandwich: sandwich }).Price,
Ingredients: _.pluck(_.where(data, { Category: category, Sandwich: sandwich }), 'Ingredient')
};
})
};
});
I'm trying to implement a queue in node js.I have an array with elements and i want at every 1 sec to insert a new one.I want to return every time only two elements from queue(at every 5 seconds).I want the queue to continue returning values from where remains.An example.I have an array [1,2,3,4].At every 2 sec i insert a new elemt in array.I return 2 elements from array at every 5 sec.Does anyone know how to make this work? Here is my code:
var queue = require('queue');
var posts=["aaa","bbbb","ccc",'ddd'];
var n=posts.length;
function populateQueue(q) {
for (var i = 0; i < posts.length; i++) {
(function(index) {
q.push(function(done) {
console.log('done', posts[index]);
setTimeout(done, 5000);
posts.splice(0,2);
});
})(i);
}
}
function insert() {
posts.push({"name":haiku()});
cxc();
}
function cxc() {
populateQueue(q2);
}
setInterval(insert,2000);
var q2 = queue({concurrency: 2});
populateQueue(q2);
q2.start();
function haiku(){
var adjs = ["autumn", "hidden", "bitter", "misty", "silent", "empty", "dry",
"dark", "summer", "icy", "delicate", "quiet", "white", "cool", "spring",
"winter", "patient", "twilight", "dawn", "crimson", "wispy", "weathered",
"blue", "billowing", "broken", "cold", "damp", "falling", "frosty", "green",
"long", "late", "lingering", "bold", "little", "morning", "muddy", "old",
"red", "rough", "still", "small", "sparkling", "throbbing", "shy",
"wandering", "withered", "wild", "black", "young", "holy", "solitary",
"fragrant", "aged", "snowy", "proud", "floral", "restless", "divine",
"polished", "ancient", "purple", "lively", "nameless"]
, nouns = ["waterfall", "river", "breeze", "moon", "rain", "wind", "sea",
"morning", "snow", "lake", "sunset", "pine", "shadow", "leaf", "dawn",
"glitter", "forest", "hill", "cloud", "meadow", "sun", "glade", "bird",
"brook", "butterfly", "bush", "dew", "dust", "field", "fire", "flower",
"firefly", "feather", "grass", "haze", "mountain", "night", "pond",
"darkness", "snowflake", "silence", "sound", "sky", "shape", "surf",
"thunder", "violet", "water", "wildflower", "wave", "water", "resonance",
"sun", "wood", "dream", "cherry", "tree", "fog", "frost", "voice", "paper",
"frog", "smoke", "star"];
return adjs[Math.floor(Math.random()*(adjs.length-1))]+"_"+nouns[Math.floor(Math.random()*(nouns.length-1))];
}
I have a quick answer to this. Specifically involving your question, but not your code. You have to tell me what your code does, otherwise I can't help you with it. But to do with your question, I have this:
First, setup your initial queue and index.
let queue = [1, 2, 3, 4, 5],
index = 0;
Now you have to declare two functions, (1) The one that enqueues values in your array. In my case, I enqueue a random number
enqueue = () => {
queue.push(Math.floor(Math.random()*10));
console.log(queue);
}
The other one gets two values at the current index, and increments the index by 2, once the storing is done. The values are then, returned.
get_two_elements = () => {
let pointed_slice = queue.slice(index, index + 2);
index += 2;
console.log(pointed_slice);
return pointed_slice;
};
Finally, to make the contraption work, you have to put timeouts on them like this
setInterval(enqueue, 2000);
setInterval(get_two_elements, 5000);
Set interval is non-blocking, thus both will happen at almost the sametime with a difference ranging between nanoseconds and milliseconds. This will successfully do what your question sounds like to me.
For reference, I placed a gist on the whole code for you here:
https://gist.github.com/jekku/012eed5ea9c356f8fa29