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);
}
Related
I'm trying to get indices of array elements. I'm going to use it for Leetcode question "Create Target Array in the Given Order".
Right now I wrote the following code but it doesn't work. (returns undefined)
var createTargetArray = function(nums) {
for(var i=0; i<nums.length; i++) {
console.log(nums.indexOf[i])
}
};
const num = [1,2,3,4,0,108];
createTargetArray(num);
Expected output from that code: [0, 1, 2, 3, 4, 5]
Am I using indexOf method incorrectly?
To get the index of the numbers, you have to call indexOf as a function call (indexOf(i))and not an array accessor (indexOf[i])
Try running the snippet below to check.
var createTargetArray = function(nums) {
for(var i=0; i<nums.length; i++) {
console.log(nums.indexOf(i))
}
};
const num = [1,2,3,4,0,108];
createTargetArray(num);
And if you want the index of exery number, that's just your variable i. You don't need to call the indexOf method.
var createTargetArray = function(nums) {
for(var i=0; i<nums.length; i++) {
console.log(i)
}
};
const num = [1,2,3,4,0,108];
createTargetArray(num);
var createTargetArray = function(nums) {
for(var i=0; i<nums.length; i++) {
console.log(nums.indexOf[i]) // <--mistake
}
};
indexOf is a method
console.log(nums.indexOf(nums[i]));
But since you are looping through the array sequentially output will always be [0, 1, 2, ... n]
I am trying to push numbers in an array into another array in groups of two.
If I have an array [1,4,3,2]; it should return [[1,4],[3,2]];
var arrayPairSum = function(nums) {
var len = nums.length / 2;
var arr = [];
for(var i = 0; i < len; i ++) {
var newArr = [];
newArr.push(nums[i]);
newArr.push(nums[i + 1]);
arr.push(newArr);
}
console.log(arr); //this should give me [[1,4],[3,2]];
};
arrayPairSum([1,4,3,2]);
can anyone see what I need to do to achieve this? I cannot figure it out.
You can use reduce method to achieve this. reduce method accepts a callback method provided on every item in the array.
In the other words, this method applies a function against an accumulator and each element in the array (from left to right) to reduce it to a single value.
var array=[1,4,3,2,8];
var contor=array.reduce(function(contor,item,i){
if(i%2==0)
contor.push([array[i],array[i+1]].filter(Boolean));
return contor;
},[]);
console.log(contor);
If you really want to iterate over the array, may skip every second index, so i+=2 ( as satpal already pointed out) :
var arrayPairSum = function(nums) {
var len = nums.length - 1;//if nums.length is not even, it would crash as youre doing nums[i+1], so thats why -1
var arr = [];
for (var i = 0; i < len; i += 2) {
var newArr = [];
newArr.push(nums[i]);
newArr.push(nums[i + 1]);
arr.push(newArr);
}
console.log(arr); //this should give me [[1,4],[3,2]];
};
arrayPairSum([1, 4, 3, 2]);
The upper one crops away every non pair at the end. If you want a single [value] at the end, may go with
len=nums.length
And check later before pushing
if(i+1<nums.length) newArr.push(nums[i+1]);
You were pretty close. Simply change the length to nums.length and in the loop increment i by 2.
var arrayPairSum = function(nums) {
var len = nums.length - 1;
var arr = [];
for(var i = 0; i < len; i+=2) {
var newArr = [];
newArr.push(nums[i]);
newArr.push(nums[i + 1]);
arr.push(newArr);
}
console.log(arr); //this should give me [[1,4],[3,2]];
};
arrayPairSum([1,4,3,2]);
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.
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.
Hi i am working on LIME programming which is a subset of javascript.
i need to use javascript.splice to remove certain elements from my array, sad to say, LIME does not support splice function.
Any idea how do i create my own function to remove elements from an array?
Thanks for your time.
EDIT: Manage to create a simple function.
function removeElements(array, index)
{
var tempArray = new Array();
var counter = 0;
for(var i = 0; i < array.length; i++)
{
if(i != index)
{
tempArray[counter] = array[i];
counter++;
}
}
return tempArray;
}
Array.prototype.splice is fully defined in ECMA-262 §15.4.4.12, so use that as your spec and write one. e.g.
15.4.4.12 Array.prototype.splice (start, deleteCount [ , item1 [ ,item2 [ , … ] ] ] )
When the splice
method is called with two or more
arguments start, deleteCount and
(optionally) item1, item2, etc., the
deleteCount elements of the array
starting at array index start are
replaced by the arguments item1,
item2, etc. An Array object containing
the deleted elements (if any) is
returned. The following steps are
taken:...
You will probably have to create a new array, copy the members up to start from the old array, insert the new members, then copy from start + deleteCount to the end to the new array.
Edit
Here is an amended splice, the first I posted was incorrect. This one splices the array passed in and returns the removed members. It looks a bit long but I tried to keep it close to the spec and not assume support for any complex Array methods or even Math.max/min. It can be simplified quite a bit if they are.
If push isn't supported, it can be replaced fairly simply too.
function arraySplice(array, start, deleteCount) {
var result = [];
var removed = [];
var argsLen = arguments.length;
var arrLen = array.length;
var i, k;
// Follow spec more or less
start = parseInt(start, 10);
deleteCount = parseInt(deleteCount, 10);
// Deal with negative start per spec
// Don't assume support for Math.min/max
if (start < 0) {
start = arrLen + start;
start = (start > 0)? start : 0;
} else {
start = (start < arrLen)? start : arrLen;
}
// Deal with deleteCount per spec
if (deleteCount < 0) deleteCount = 0;
if (deleteCount > (arrLen - start)) {
deleteCount = arrLen - start;
}
// Copy members up to start
for (i = 0; i < start; i++) {
result[i] = array[i];
}
// Add new elements supplied as args
for (i = 3; i < argsLen; i++) {
result.push(arguments[i]);
}
// Copy removed items to removed array
for (i = start; i < start + deleteCount; i++) {
removed.push(array[i]);
}
// Add those after start + deleteCount
for (i = start + (deleteCount || 0); i < arrLen; i++) {
result.push(array[i]);
}
// Update original array
array.length = 0;
i = result.length;
while (i--) {
array[i] = result[i];
}
// Return array of removed elements
return removed;
}
If you don't care about order of the array and you're just looking for a function to perform splice, here's an example.
/**
* Time Complexity: O(count) aka: O(1)
*/
function mySplice(array, start, count) {
if (typeof count == 'undefined') count = 1
while (count--) {
var index2remove = start + count
array[index2remove] = array.pop()
}
return array
}
If you want to return the removed elements like the normal splice method does this will work:
/**
* Time Complexity: O(count) aka: O(1)
*/
function mySplice(array, index, count) {
if (typeof count == 'undefined') count = 1
var removed = []
while (count--) {
var index2remove = index + count
removed.push(array[index2remove])
array[index2remove] = array.pop()
}
// for (var i = index; i < index + count; i++) {
// removed.push(array[i])
// array[i] = array.pop()
// }
return removed
}
This modifies the original Array, and returns the items that were removed, just like the original.
Array.prototype.newSplice = function( start, toRemove, insert ) {
var remove = this.slice( start, start + toRemove );
var temp = this.slice(0,start).concat( insert, this.slice( start + toRemove ) );
this.length = 0;
this.push.apply( this, temp );
return remove;
};
Comparison test: http://jsfiddle.net/wxGDd/
var arr = [0,1,2,3,4,5,6,7,8];
var arr2 = [0,1,2,3,4,5,6,7,8];
console.log( arr.splice( 3, 2, 6 ) ); // [3, 4]
console.log( arr ); // [0, 1, 2, 6, 5, 6, 7, 8]
console.log( arr2.newSplice( 3, 2, 6 ) ); // [3, 4]
console.log( arr2 ); // [0, 1, 2, 6, 5, 6, 7, 8]
It could use a little extra detail work, but for the most part it takes care of it.
Here is a simple implement in case the Array.prototype.splice dispears
if (typeof Array.prototype.splice === 'undefined') {
Array.prototype.splice = function (index, howmany, elemes) {
howmany = typeof howmany === 'undefined' || this.length;
var elems = Array.prototype.slice.call(arguments, 2), newArr = this.slice(0, index), last = this.slice(index + howmany);
newArr = newArr.concat.apply(newArr, elems);
newArr = newArr.concat.apply(newArr, last);
return newArr;
}
}
Are there any other methods that are missing in LIME's Array implementation?
Assuming at least the most basic push() and indexOf() is available, there's several ways you could do it. How this is done would depend on whether this is destructive method or whether it should return a new array. Assuming the same input as the standard splice(index, howMany, element1, elementN) method:
Create a new array named new
push() indexes 0 to index onto the new array
Now stop at index and push() any new elements passed in. If LIME supports the standard arguments variable then you can loop through arguments with index > 2. Otherwise you'll need to pass in an array instead of a variable number of parameters.
After inserting the new objects, continue looping through the input array's elements, starting at index + howMany and going until input.length
I believe that should get you the results you're looking for.
I have used this below function as an alternative for splice()
array = mySplice(array,index,count);
above is the function call,
And this is my function mySplice()
function mySplice(array, index, count)
{
var newArray = [];
if( count > 0 )
{ count--;}
else
{ count++;}
for(i = 0; i <array.length; i++)
{
if(!((i <= index + count && i >= index) || (i <= index && i >= index + count)))
{
newArray.push(array[i])
}
}
return newArray;
}
I have done it very similar way using only one for loop
function removeElements(a,index,n){
// a=> Array , index=> index value from array to delete
// n=> number of elements you want to delete
let temp = []; // for storing deleted elements
let main_array = []; // for remaining elements which are not deleted
let k = 0;
for(let i=0;i<a.length;i++){
if((i===index) || ((index<i && i<n+index))){
temp[i]=a[i+1];
delete a[i];
}
if(a[i]!==undefined){
main_array[k] = a[i];
a[i] = main_array[k];
k++;
}
}
a=main_array;
return a;
}
a=[1,2,3,4,5];
console.log(removeElements(a,0,1));
follow link Jsfiddle
var a = [3, 2, 5, 6, 7];
var fromindex = 1
var toindex = 2;
for (var i = 0; i < a.length; i++) {
if (i >= fromindex + toindex || i < fromindex) {
console.log(a[i])
}
}
var a = [3, 2, 5, 6, 7];
var temp=[];
function splice(fromindex,toindex)
{
for (var i = 0; i < a.length; i++) {
if(i>=fromindex+toindex || i<fromindex)
{
temp.push(a[i])
}
}
return temp
}
console.log(splice(3,2))