I am trying to iterate in an array
[1,2,3,4,5,6]
And I want to store them in an object so that:
[
{1},
{1,2},
{1,2,3},
{2,3,4},
{3,4,5},
{4,5,6}
]
As you may notice, the first element to be pushed in the array is removed first if the limit of 3 was reached.
I'm doing this:
var given = [1,2,3,4,5,6];
var limit = 3;
var start = 1;
var result = [];
for (var i = 0; i < given.length; i++) {
var j = 0;
while(j <= start) {
j++;
if(start <= limit) {start++};
result.push(given[i]);
}
};
console.log(result);
Seems like my answer is super wrong, i'm still stuck at pushing it 1 by 1 then increase. So i haven't yet, think of replacing the oldest element.
EDIT:
Also I'm thinking of not shifting the array and put the new value to the end instead replace the value and maintain their indexes...
i mean
[
{1},
{1,2},
{1,2,3},
{4,2,3},
{4,5,3},
{4,5,6}
]
Try
var given = [1, 2, 3, 4, 5, 6];
var limit = 3;
var start = 1;
var result = [], rec = [];
for (var i = 0; i < given.length; i++) {
rec = rec.slice(0);
if(rec.length == limit){
rec.shift();
}
rec.push(given[i]);
result.push(rec)
}
console.log(JSON.stringify(result));
Demo: Fiddle
O/P
[[1],[1,2],[1,2,3],[2,3,4],[3,4,5]]
Update
var given = [1, 2, 3, 4, 5, 6];
var limit = 3;
var start = 1;
var result = [],
rec = [];
for (var i = 0; i < given.length; i++) {
rec = rec.slice(0);
rec[i % limit] = given[i]
result.push(rec)
}
console.log(JSON.stringify(result));
Demo: Fiddle
O/P
[[1],[1,2],[1,2,3],[4,2,3],[4,5,3],[4,5,6]]
Related
So I have this function where I've need to take out the evens and odds and put them into separate arrays but I need the evens array to print first rather than the odds.
var numbersArray = [1,2,34,54,55,34,32,11,19,17,54,66,13];
function divider(numbersArray) {
var evensOdds = [[], []];
for (var i = 0; i < numbersArray.length; i++) {
evensOdds[i & 1].push(numbersArray[i]);
}
return evensOdds;
}
If you want to split the number by their even and odd values, instead of using the index (i), determine the sub array to push into using the value - numbersArray[i] % 2.
var numbersArray = [1,2,34,54,55,34,32,11,19,17,54,66,13];
function divider(numbersArray) {
var evensOdds = [[], []];
for (var i = 0; i < numbersArray.length; i++) {
evensOdds[numbersArray[i] % 2].push(numbersArray[i]);
}
return evensOdds;
}
console.log(divider(numbersArray));
If you want to split them by even and odd indexes use (i + 1) % 2 to determine the sub array to push into:
var numbersArray = [1,2,34,54,55,34,32,11,19,17,54,66,13];
function divider(numbersArray) {
var evensOdds = [[], []];
for (var i = 0; i < numbersArray.length; i++) {
evensOdds[(i + 1) % 2].push(numbersArray[i]);
}
return evensOdds;
}
console.log(divider(numbersArray));
Just for fun, a forEach version of the accepted answer.
var numbersArray = [1,2,34,54,55,34,32,11,19,17,54,66,13];
var even_odd = [ [], [] ];
numbersArray.forEach( e => even_odd[e%2].push(e) );
console.log(even_odd);
I have a random generator from 1 to 10 that produces non repeating values
I am trying to get the previous value.
So if current is 5 and then 8
Previous 8 and next is 9, etc
This is my code:
var randomNumbers = [];
var numRandoms = 11;
var myVar = setInterval(randomUnique1to10, 5000);
function randomUnique1to10() {
// refill the array if needed
if (!randomNumbers.length) {
for (var i = 1; i < numRandoms; i++) {
randomNumbers.push(i);
}
}
var index = Math.floor(Math.random() * randomNumbers.length);
var val = randomNumbers[index];
if (i === 1) { // i would become 0
i = randomNumbers.length; // so put it at the other end of the array
}
i = i - 1; // decrease by one
previous = randomNumbers[i]; // give us back the item of where we are now
randomNumbers.splice(index, 1);
Thank you
This is totally what you're looking for. Hope it helps!.
var randomNumbers = [];
var numRandoms = 11;
var myVar = setInterval(randomUnique1to10, 1000);
shuffle = function(o){
for(var j, x, i = o.length; i; j = parseInt(Math.random() * i), x = o[--i], o[i] = o[j], o[j] = x);
return o;
};
var finalArray = shuffle([1, 2, 3, 4,5,6,7,8,9,10]);
function randomUnique1to10() {
// refill the array if needed
if (!randomNumbers.length) {
for (var i = 1, l = 11; i < l; i++) { }
}
// var finalArray = shuffle(randomNumbers);
document.write(finalArray + "<br/>");
randomNumbers = finalArray;
var index = Math.floor(Math.random() * randomNumbers.length);
var val = randomNumbers[index];
if (i === 1) { // i would become 0
i = randomNumbers.length; // so put it at the other end of the array
}
x = index-1; // decrease by one
current = randomNumbers[randomNumbers.length - 1]; // give us back the item of where we are now
previous = randomNumbers[randomNumbers.length - 2];
if(previous === undefined)
{
previous = "n/a";
}
randomNumbers.pop();
if(randomNumbers.length <= 0){
finalArray = shuffle([1, 2, 3, 4,5,6,7,8,9,10]);
}
document.write("Current >> " + current + " and previous = " +previous + "<br/>")
}
try this:
var randomNumbers = [];
var numRandoms = 11;
var myVar = setInterval(randomUnique1to10, 5000);
var x;
function randomUnique1to10() {
// refill the array if needed
if (!randomNumbers.length) {
for (var i = 1; i < numRandoms; i++) {
randomNumbers.push(i);
}
}
var index = Math.floor(Math.random() * randomNumbers.length);
var val = randomNumbers[index];
if (i === 1) { // i would become 0
i = randomNumbers.length; // so put it at the other end of the array
}
x = index-1; // decrease by one
previous = randomNumbers[x]; // give us back the item of where we are now
var res = randomNumbers.splice(index, 1);
console.log("result: "+res);
console.log("prev : "+previous);
console.log("Rand : "+randomNumbers);
}
NOTE:
this code have, one problem, if res = min(array) then prev will become unidentify
The question lack a bit of clarity. From the question what I understood is,
The values in the array are non repeating
You have a value at variable current and you want to find the previous value of the current which is stored in the array
And I will answer from what I understood. Using indexOf() gives you the index of current element from the array and you just need to subtract 1 from it to get the previous.
var array = [1, 9, 2, 8, 3, 7, 4, 6, 5];
var current = 8;
var currentIndex = array.indexOf(current);
var previous = currentIndex !== 0 ? array[currentIndex-1] : 'N/A';
document.write('Previous Value: ', previous)
I have a question . How do you retrieve elements that has no double value in an array?? For example: [1,1,2,2,3,4,4,5] then you retrieve [3,5] only.
Thanks in advance
for (var j = 0; j < newArr.length; j++) {
if ((arr1.indexOf(newArr[j]) === 0) && (arr2.indexOf(newArr[j]) === 0)) {
index = newArr.indexOf(j); newArr.splice(index, 1);
}
}
If the item in the array is unique then the index found from the beginning should equal the index found from the end, in other words:
var xs = [1, 1, 2, 2, 3, 4, 4, 5];
var result = xs.filter(function(x) {
return xs.indexOf(x) === xs.lastIndexOf(x);
});
console.log(result); //=> [3, 5]
sorry for the presentation its my first post !
You have to compare each element of your array to the others in order to get the number of occurence of each element
var tab = [1,1,2,2,3,4,4,5] //The array to analyze
tab = tab.sort(); // we sort the array
show(tab); // we display the array to the console (F12 to open it)
var uniqueElementTab = []; // this array will contain all single occurence
var sameElementCounter = 0;
for(x=0;x<tab.length;x++){ // for all element in the array
sameElementCounter = 0;
for(y=0;y<tab.length;y++){ // we compare it to the others
if((tab[x]==tab[y])){
sameElementCounter+=1; // +1 each time we meet the element elsewhere
}
}
if(sameElementCounter<=1){
uniqueElementTab.push(tab[x]); //if the element is unique we add it to a new array
}
}
show(uniqueElementTab); // display result
function show(tab) { // Simple function to display the content of an array
var st="";
for(i=0;i<tab.length;i++){
st += tab[i]+" ";
}
console.log(st+"\n");
}
Hope it helps.
Here is a simple "tricky" solution using Array.sort, Array.join, Array.map, String.replace and String.split functions:
var arr = [1, 1, 2, 2, 3, 4, 4, 5];
arr.sort();
var unique = arr.join("").replace(/(\d)\1+/g, "").split("").map(Number);
console.log(unique); // [3, 5]
create new array tmp,and check already value exist by indexOf .If existed delete by splice function..
var arr = [1,1,2,2,3,4,4,5];
var tmp = [];
var dup = [];
for(var i = 0; i < arr.length; i++){
var ind = tmp.indexOf(arr[i]);
if(ind == -1){
if(dup.indexOf(arr[i]) == -1){
tmp.push(arr[i]);
}
}
else{
tmp.splice(ind,1);
dup.push(arr[i]);
}
}
console.log(tmp);
This would be my way of doing this job.
var arr = [1,1,2,2,3,4,4,5],
uniques = Object.keys(arr.reduce((p,c) => (c in p ? Object.defineProperty(p, c, {enumerable : false,
writable : true,
configurable : true})
: p[c] = c,
p), {}));
console.log(uniques);
A solution for unsorted arrays with a hash table for the items. Complexity O(2n)
var array = [1, 1, 2, 2, 3, 4, 4, 5, 1],
hash = Object.create(null),
single;
array.forEach(function (a, i) {
hash[a] = a in hash ? -1 : i;
});
single = array.filter(function (a, i) {
return hash[a] === i;
});
console.log(single);
If the array is sorted, you can solve this in O(n) (see "pushUniqueSinglePass" below):
function pushUniqueSinglePass(array, unique) {
var prev; // last element seen
var run = 0; // number of times it has been seen
for (var i = 0; i < array.length; i++) {
if (array[i] != prev) {
if (run == 1) {
unique.push(prev); // "prev" appears only once
}
prev = array[i];
run = 1;
} else {
run++;
}
}
}
function pushUniqueWithSet(array, unique) {
var set = new Set();
for (var i = 0; i < array.length; i++) {
set.add(array[i]);
}
for (let e of set) {
unique.push(set);
}
}
// Utility and test functions
function randomSortedArray(n, max) {
var array = [];
for (var i = 0; i < n; i++) {
array.push(Math.floor(max * Math.random()));
}
return array.sort();
}
function runtest(i) {
var array = randomSortedArray(i, i / 2);
var r1 = [],
r2 = [];
console.log("Size: " + i);
console.log("Single-pass: " + time(
pushUniqueSinglePass, array, r1));
console.log("With set: " + time(
pushUniqueWithSet, array, r2));
// missing - assert r1 == r2
}
[10, 100, 1000, 10000,
100000, 1000000
].forEach(runtest);
function time(fun, array, unique) {
var start = new Date().getTime();
fun(array, unique);
return new Date().getTime() - start;
}
This is much more efficient than using maps or sorting (time it!). In my machine, a 1M sorted array can have its unique elements found in 18 ms; while the version that uses a set requires 10x more.
I am working on a code where I need to reverse certain no of elements in an array and rest should remain same. For example is an array has values of 1,2,3,4,5,6 and I have to reverse 4 elements of it then output should be 4,3,2,1,5,6. I am using below code to achieve this but getting error, please suggest.
function reverseArray(n, a) {
var interimArray1 = [];
//var interimArray2=[];
//var finalArray=[];
for (var i < n; i >= 0; i--) {
interimArray1.push[a[i]];
}
for (var i = n; i < a.length; i++) {
interimArray1.push[a[i]];
}
for (var i = 0; i < interimArray1.length; i++) {
console.log(interimArray1[i]);
}
}
var arr = [1, 2, 3, 4, 5, 6];
var num = 4;
reverseArray(num, arr);
The error in your code is that you intend to call the push method on a[i] like so:
interimArray1.push(a[i]);
but instead you write:
interimArray1.push[a[i]];
You make that mistake twice. To give arguments to the push method, you must use round parenthesis ().
With that fixed, you will see that your code works perfectly.
You can use Array#slice, Array#splice as follow.
function partialReverse(arr, num, from = 0) {
var slicedArr = arr.slice(from, num + from);
arr.splice(from, num); // Remove `num` items from array
arr.splice(from, 0, ...slicedArr.reverse()); // Add `num` reversed items
return arr;
}
var arr = [1, 2, 3, 4, 5, 6];
console.log(partialReverse(arr, 4, 0)); // Reverse four items from `arr` starting from 0th index
console.log(partialReverse(arr, 4, 1)); // Reverse four items from `arr` starting from 1st index
Lots of hints but you seem to be missing them. ;-)
You need to assign an initial value to i, so:
for (var i = n; ... )
===========^
Also, you need to use () to call functions, not [], so:
interimArray1.push(a[i]);
==================^====^
Same in the following for block. Otherwise, the code works though it's more verbose than it needs to be.
This is working :
I'm sure there are faster ways of doing it. Also, it will only work for elements at the beginning of the array but you can adjust the function for what you want to achieve.
var reverseArray = function(arr,elementsToReverse) {
var tempArrayRev = [];
var tempArray = [];
for (var i=0;i<arr.length;i++) {
if (i < elementsToReverse) {
tempArrayRev[i] = arr[i];
} else {
tempArray.push(arr[i]);
}
}
return tempArrayRev.reverse().concat(tempArray);
}
var array = [1,2,3,4,5,6];
document.getElementById('arrayOutput').innerHTML += reverseArray(array,4);
<div id="arrayOutput">Array :<br></div>
This is the answer you can test it.
function reverseArray(n, a) {
var interimArray1 = [];
for (var i = 0; i < a.length; i++) {
interimArray1.push(a[i]);
}
for (var i = num; i >=0; i--) {
interimArray1[i-1] = a[n - i];
}
for (var i = 0; i < interimArray1.length; i++) {
console.log(interimArray1[i]);
}
}
var arr = [1, 2, 3, 4, 5, 6];
var num = 4;
reverseArray(num, arr);
You could use something like this.
function reverseArray(n, arrIn) {
// Splice splits the array in 2 starting at 0 index going n long
var arrOut = arrIn.splice(0,n);
// reverse is pretty straight forward
arrOut = arrOut.reverse();
// Concat joins the two together
return arrOut.concat(arrIn);
}
Forgive me if this question has been asked, but I can't seem to find it.
I am attempting to create an array and reverse it (without using reverse)
This bit of code works perfect:
function reverseArrayInPlace(array) {
for (var i = 0; i < Math.floor(array.length / 2); i++) {
var old = array[i];
array[i] = array[array.length - 1 - i];
array[array.length - 1 - i] = old;
}
return array;
}
var arrayValue = [1, 2, 3, 4, 5];
reverseArrayInPlace(arrayValue);
console.log(arrayValue);
// → [5, 4, 3, 2, 1]
As you can see, it takes an in an array, does some logic, and returns the same altered array.
Although, it doesn't make sense to me why this code doesn't work:
var some_array = [6,7,8,9,10];
function reverseArrayInPlace(array) {
var replacement_array = [];
for (var i = 0; i < some_array.length; i++)
replacement_array.unshift(array[i])
array = replacement_array;
return array;
}
reverseArrayInPlace(some_array);
console.log(some_array);
// → [ 6, 7, 8, 9, 10 ]
This code also takes in an array, does some logic (and assignment) and returns an array back. Why doesn't it alter the global variable like the first one? Is there any way to change it so that it can?
Ok,you need this:
function reverseArrayInPlace(array) {
replacement_array = [];
for (var i = 0; i <array.length; i++)
{
replacement_array.unshift(array[i])
}
for(var i = 0; i <array.length; i++){
array[i]=replacement_array[i]
}
return array;
}
some_array = [6,7,8,9,10];
reverseArrayInPlace(some_array)
console.log(some_array)
Replace the variable's content will work.
Stepping through the code:
function reverseArrayInPlace(array) {
var replacement_array = [];
for (var i = 0; i < some_array.length; i++)
replacement_array.unshift(array[i])
At this point you have created a new array that's the reverse of the original array.
array = replacement_array;
Assigning a new value to array will not alter the original array; only mutable array methods or element dereferencing can effect that.
return array;
}
You're returning the new array here, so you can perform an assignment outside of the function:
some_array = reverseArrayInPlace(some_array);
console.log(some_array);
However, that no longer qualifies as modifying an array in-place; you can use unshift() and splice() though:
for (var i = 1, n = array.length; i < n; ++i) {
array.unshift(array.splice(i, 1)[0]);
}
To affect the global directly:
var some_array = [6,7,8,9,10];
function reverseArrayInPlace(array) {
var replacement_array = [];
for (var i = 0; i < array.length; i++)
replacement_array.unshift(array[i]);
for (var i = 0; i < array.length; i++)
array[i] = replacement_array[i];
}
reverseArrayInPlace(some_array);
alert(some_array);
You don't need to return array.