Making a project which involves generating random numbers, which is easy enough with Math.random(). A new number will be generated every n seconds, and i want to be able to display the 5 most recent numbers.
The best I could come up with is creating an array with all the generated numbers, pushing new ones, and then getting the 5 most recent indexes.
Is there a better way to only store only the 5 most recent, as there will be thousands of these numbers being generated?
The best I could come up with is creating an array with all the
generated numbers, pushing new ones, and then getting the 5 most
recent indexes.
Rather than just pushing, do shift and push
var randomArr = [];
function addRandom()
{
//var newNum = randomNumber();
if ( randomArr.length >= 5 )
{
randomArr.shift();
}
randomArr.push( newNum );
}
Now you don't need to do a splice, just take the randomArr array as is.
try this:
var array = [Math.random(), Math.random(), Math.random(), Math.random(), Math.random()];
function addToArray() {
array.push(Math.random());
array.shift();
}
function getLast5() {
return array;
}
Logic Maybe like below just do it with random numbers I am showing you with fixed numbers to make it more clear what is happening behind the scene
var randomNumbers= [];
randomNumbers.push(2); // randomNumbers is now [2]
randomNumbers.push(5); // randomNumbers is now [2, 5]
randomNumbers.push(7); // randomNumbers is now [2, 5, 7]
randomNumbers.push(9); // randomNumbers is now [2, 5, 7, 9]
randomNumbers.push(1); // randomNumbers is now [2, 5, 7, 9, 1]
randomNumbers.shift(); // randomNumbers is now [5, 7, 9, 1]
randomNumbers.push(10); // randomNumbers is now [5, 7, 9, 1, 10]
With ECMAScript2016, you can do:
var arr = [1, 2, 3];
var newNumber = 4;
arr = [ ...arr.slice(1), newNumber ];
console.log(arr);
Related
I am trying to write an JS algorithm in which I have two arrays.
The value of the first one will have different numerical values. The second array will be constant, say for example [5, 3, 6, 8].
Now I would like to multiply the values from the first array, by the corresponding index value from the second array, so having for example such a first array: [3, 7, 2, 5] it would look like this: 5*3, 3*7, 6*2, 8*5.
From the result I would like to create a new array, which in this case is [15, 21, 12, 40].
How can I achieve this result?
You can use map() and use the optional parameter index which is the index of the current element being processed in the array:
const arr1 = [3, 4, 5, 6];
const arr2 = [7, 8, 9, 10];
const mulArrays = (arr1, arr2) => {
return arr1.map((e, index) => e * arr2[index]);
}
console.log(mulArrays(arr1, arr2));
This is assuming both arrays are of the same length.
You can simply use for loop -
var arr1 = [5, 3, 6, 8];
var arr2 = [3, 7, 2, 5];
var finalArr = [];
for (var i = 0; i < arr1.length; i++) {
finalArr[i] = arr1[i] * arr2[i];
}
console.log(finalArr);
Im trying to copy elements of arr1 into arr2 at index n. The elements must be copied in the exact order they're in. I can get the code to work when I loop through the arrow backwards but I cant pass the tests because its not in order.
function frankenSplice(arr1, arr2, n) {
let newArr = arr2.splice(" ");
for(let i = 0; i < arr1.length;i++) {
newArr.splice(n,0,arr1[i]);
}
return console.log(newArr);
}
An example of how this should be called is frankenSplice([1, 2, 3], [4, 5, 6], 1);
Expected output is [4, 1, 2, 3, 5]
I keep getting [ 4, 1, 2, 3, 5, 6 ]
The reason your output is coming backwards is because you keep inserting at the same position n. This pushes the previous element after it, so they end up in reverse order. If you increment n each time through the loop, you'll insert them in order.
But there's no need for a loop, use spread syntax to use all of arr1 as the arguments in a single call to splice().
function frankenSplice(arr1, arr2, n) {
let newArr = [...arr2]; // make copy of arr2
newArr.splice(n, 0, ...arr1); // splice arr1 into the copy
return newArr;
}
console.log(frankenSplice([1, 2, 3], [4, 5, 6], 1));
I don't understand why you don't expect 6 in the output.
Not sure why the 6 is getting deleted but maybe something like this:
function frankenSplice(arr1, arr2, n) {
let newArr = arr2
newArr.splice(n+1)
for(let i = arr1.length - 1; i >= 0; i--) {
newArr.splice(n,0,arr1[i]);
}
return console.log(newArr);
}
frankenSplice([1, 2, 3], [4, 5, 6], 1);
I have an n-dimensional array and I want to access/modify an element in it using another array to specify the indices.
I figured out how to access a value, however I do not know how to modify the original value.
// Arbitrary values and shape
arr = [[[8, 5, 8],
[9, 9, 9],
[0, 0, 1]],
[[7, 8, 2],
[9, 8, 3],
[9, 5, 6]]];
// Arbitrary values and length
index = [1, 2, 0];
// The following finds the value of arr[1][2][0]
// Where [1][2][0] is specified by the array "index"
tmp=arr.concat();
for(i = 0; i < index.length - 1; i++){
tmp = tmp[index[i]];
}
// The correct result of 9 is returned
result = tmp[index[index.length - 1]];
How can I modify a value in the array?
Is there a better/more efficient way to access a value?
This is a classic recursive algorithm, as each step includes the same algorithm:
Pop the first index from indices.
Keep going with the array that the newly-popped index points to.
Until you get to the last element in indices - then replace the relevant element in the lowest-level array.
function getUpdatedArray(inputArray, indices, valueToReplace) {
const ans = [...inputArray];
const nextIndices = [...indices];
const currIndex = nextIndices.shift();
let newValue = valueToReplace;
if (nextIndices.length > 0) {
newValue = getUpdatedArray(
inputArray[currIndex],
nextIndices,
valueToReplace,
);
} else if (Array.isArray(inputArray[currIndex])) {
throw new Error('Indices array points an array');
}
ans.splice(currIndex, 1, newValue);
return ans;
}
const arr = [
[
[8, 5, 8],
[9, 9, 9],
[0, 0, 1]
],
[
[7, 8, 2],
[9, 8, 3],
[9, 5, 6]
]
];
const indices = [1, 2, 0];
const newArr = getUpdatedArray(arr, indices, 100)
console.log(newArr);
You can change the values in array like this,
arr[x][y][z] = value;
Does this help?
I think what you're looking for is this:
arr[index[0]][index[1]][index[2]] = value;
I'm having trouble understanding what you're attempting to do in the second part of your example.
For the life of me I can't figure out how to duplicate the numbers array.
Expected result: [1, 2, 3, 4, 5, 1, 2, 3, 4, 5]
Here is my code so far:
const numbers = [1, 2, 3, 4, 5];
var result = numbers.map((number) => {
return number
});
console.log(result);
I can't figure out how you can take the numbers array and then duplicate the array?
I was starting to do if statements - "If number is equal to 1 then return 1" but that would print the numbers like this [1, 1, 2, 2, 3, 3, 4, 4, 5, 5]
https://jsfiddle.net/e6jf74n7/1/
Map will map all values one-to-one, that's why it's called "map"; it gives you one value, you return a value that should replace it.
To duplicate a list, concat the list to itself:
const numbers = [1, 2, 3, 4, 5];
var result = numbers.concat(numbers);
console.log(result);
fastest way is to use slice() then concat() to old array.
var arr = [ 1, 2, 3, 4, 5 ];
var clone = arr.slice(0);
var duplicate = arr.concat(clone);
Map won't work in this case just use concat
numbers.concat(numbers);
If you want to concat multiple times then
var concatArr = numbers;
for (var i=0; i < 9 ; i++ ) {
numbers = numbers.concat(concatArr);
}
console.log(numbers);
Concat docs
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/concat
I have the following array:
var array = [
[1, 2, 3, 4, 5],
[2, 3],
[3, 4],
[3]
];
I'm trying to end up with a unique set of numbers from the arrays that appear in all arrays.
Therefore in this case returning
[3]
Any suggestions?
Many thanks :)
Store the value of array[0] in a variable (let's call it result).
Loop from array[1] to the end.
In this loop, run through all the values of result. If the current value of result is not in array[x] remove this value from result.
At the end of the loop, result only contains the desired values.
Aside from the obvious "iterate over every array and find matching numbers in every other array" you could flatten (concat) the original array, sort it, then look for numbers that occur at four consecutive indexes. I'm not a fan of questions where OP doesn't show any effort, but this was quite fun, so here it goes
array.reduce(function(prev, cur){
return prev.concat(cur);
})
.sort()
.filter(function(item, i, arr){
return arr[ i + array.length - 1 ] === item;
});
Or ES2015:
array.reduce((prev, cur)=>prev.concat(cur))
.sort()
.filter((i, idx, arr)=>(arr[idx+array.length-1]===i));
After learning i was using the wrong javascript method to remove from an array (pop) and some more tinkering. I got it working many thanks for those who responded.
var array = [
[2, 3, 5, 1],
[3, 4, 2, 1],
[3, 2],
[3, 4, 2, 5]
];
var result = array[0]
for (var i = 1; i < array.length; i++) {
for (var j = 0; j < result.length; j++) {
var arrayQuery = $.inArray(result[j], array[i]);
if(arrayQuery == -1){
result.splice(j, 1)
}
};
};
Try this:
var array = [
[1, 2, 3, 4, 5],
[2, 3],
[3, 4],
[3]
];
var arr = [];
for(var x in array){
for(var y in array[x]){
if(arr.indexOf(array[x][y]) === -1){
arr.push(array[x][y]);
}
}
}
console.log(arr);
Output:
[1, 2, 3, 4, 5]
Working Demo