This question already has answers here:
How can I remove a specific item from an array in JavaScript?
(142 answers)
Closed 1 year ago.
How can I check whether an array contains a value, and if so, remove it?
PS: For this exercise, I'm not allowed to use anything more than than .pop, .push and .length array functions.
My logic is the following: if the specified value is within the array, reorder the array so that the last element of it will contain this value, then remove it with .pop. But how can I find this value and reorder it without using anything more than those array functions I specified above?
This is what I managed to come up with so far:
let array_1 = [1,2,3];
if (array_1 == 2){
//reorder somehow
array_1.pop();
}
console.log(array_1);
Using this approach, you are not creating a new array but modifying it. It uses .pop().
let array_1 = [1, 2, 3];
// Iterate all array
for (let i = 0; i < array_1.length; i++) {
// While there is a 2 element in the actual index, move all elements (from i index) to the previous index
while(array_1[i] === 2) {
for (let j = i; j < array_1.length - 1; j++) {
array_1[j] = array_1[j + 1];
}
// Now remove the last element (since we move all elements to the previous index)
array_1.pop();
}
}
console.log(array_1);
Here a snippet so you can try it
let array_1 = [1, 2, 3, 4, 2, 5, 2, 6, 2];
for (let i = 0; i < array_1.length; i++) {
while(array_1[i] === 2) {
for (let j = i; j < array_1.length - 1; j++) {
array_1[j] = array_1[j + 1];
}
array_1.pop();
}
}
console.log(array_1);
This would mantain the order of the array, but without the "2" elements.
Here's another option using pop
const filter = (array, target) => {
const newArray = [];
let tmp;
while(tmp = array.pop()) {
if (tmp !== target) {
newArray.push(tmp)
}
}
console.log(newArray)
return newArray;
}
filter([1,2,3,4], 2) // [4, 3, 1] Note that it reversed the order of the array!
If you are limited to pop, push and length, you can loop over all elements, check if a given element matches the value you are looking for, and add them to a new array using push.
let array_1 = [1,2,3];
let newArray = [];
for (let i = 0; i < array_1.length; i++) {
if (array_1[i] !== 2) {
newArray.push(array_1[i]);
}
}
console.log(newArray);
// using splice
// splice(indexStart, how many, replace with)
// example :
let arr = [0,1,2,3,4,5];
// remove at index 1
arr.splice(1,1);
console.log( arr );
// replace at index 1
arr.splice(1,1,"new 1");
console.log( arr );
// merge index 2 and 3
arr.splice(2,2,"merge 2 and 3");
console.log( arr );
// create 2 new items start at index 2
arr.splice(2,2,"new 2", "new 3");
console.log( arr );
Related
I have a three-dimensional array, for example:
var array = [[1,0][3,3][2,1][0,8]]
and I want to do something with the first item in each sub-array, but something else with the second item in each sub-array.
So, for example, I would like to find the sum of array[0][0], array[1][0], array[2][0] and so on for array.length. But, I would like a separate result for array[0][1], array[1][1], array[2][1], etc.
I'm still learning javascript (very slowly) and, if possible, I would like to be pointed in the right direction, rather than getting a ready-made solution. I've been looking for possible solutions, and I think I may need a nested for loop, but I'm not sure how to structure it to get all the values.
I've been trying something along the lines of:
for (var i = 0; i < array.length; i++) {
for (var j = 0; j < array.length; j++) {
return array[i][j];
}
}
but I don't understand what's happening well enough to manipulate the result.
If anyone could steer me in the right direction toward finding a solution, that'd be much appreciated.
Thanks in advance.
You might consider using .reduce - on each iteration, add the first array value to a property of the accumulator, and do whatever you need to with the second array value, assigning its result to another property of the accumulator. For example, let's say for the second items, you wanted to get their product:
const input = [[1,0],[3,3],[2,1],[0,8]];
const { sum, product } = input
.reduce(({ sum=0, product=1 }, [item0, item1]) => ({
sum: sum + item0,
product: product * item1
}), {});
console.log(sum, product);
In the above code, the accumulator is an object with two properties, sum (starts at 0) and product (starts at 1). Inside the reduce, an object is returned, with the new sum being the old sum plus the first item in the array, and with the new product being the old product multiplied by the second item in the array. (of course, the resulting product is 0 because in the first sub-array, the second item is 0)
Also note that arrays always need commas separating each array item - you need to fix your input array's syntax.
Of course, you can also for loops if you have to, but I think array methods are preferable because they're more functional, have better abstraction, and don't require manual iteration. The same code with a for loop would look like this:
const input = [[1,0],[3,3],[2,1],[0,8]];
let sum = 0;
let product = 1;
for (let i = 0; i < input.length; i++) {
const [item0, item1] = input[i];
sum += item0;
product *= item1;
}
console.log(sum, product);
You just need one for-loop since you just have one array with arrays inside where you know the indexes you want to proccess. So it would be something as follows:
let sum1 = 0;
let sum2 = 0;
for(let i = 0; i < array.length; i++) {
sum1 += array[i][0];
sum2 += array[i][1];
}
console.log('sum1: ', sum1);
console.log('sum2: ', sum2);
Firstly the array you have posted is a 2d array not a 3d array.
And the nested for loop you have posted is perfect for what you want.
Your first for statment is looping through the the frist deminsion of your array. the second is getting each index in the second array
var array = [[1,0],[3,3],[2,1],[0,8]]
for (var i = 0; i < array.length; i++) {
//This loop over these [1,0],[3,3],[2,1],[0,8]
//So i on the first loop is this object [1,0] so so on
for (var j = 0; j < array.length; j++) {
//This will loop over the i object
//First loop j will be 1
//Here is where you would do something with the index i,j.
//Right now you are just returning 1 on the first loop
return array[i][j];
}
}
I hope this help your understanding
Since you asked for help with pointing you in the right direction, I would suggest you start with simple console.logs to see what's happening (comments are inline):
var array = [[1, 0],[3, 3],[2, 1],[0, 8]];
var results = [0, 0]; // this array is to store the results of our computation
for (var i = 0; i < array.length; i++) { // for each subarray in array
console.log('examining subarray ', array[i]);
for (var j = 0; j < array[i].length; j++) { // for each element in subarray
if (j === 0) {
console.log('... do something with the first element of this array, which is: ' + array[i][j]);
results[j] += array[i][j]
} else if (j === 1) {
console.log('... do something with the second element of this array, which is: ' + array[i][j]);
// do some other computation and store it in results
}
}
}
console.log('Final results are ', results);
You made a mistake on the second line. You need to iterate through the nested array and then take the value from the main array.
const mainArray = [[1, 0], [3, 3], [2, 1], [0, 8]];
for (let i = 0; i < mainArray.length; i++) {
const nestedArray = mainArray[i]
for (let j = 0; j < nestedArray.length; j++) {
const value = mainArray[i][j]
switch(j) {
case 0:
console.log(`first item of array number ${i+1} has value: ${value}`)
break;
case 1:
console.log(`second item of array number ${i+1} has value: ${value}`)
break;
}
}
}
You can use a for...of loop along with destructuring like so:
for(let [a, b] of array) {
// a will be the first item from the subarrays: array[0][0], array[1][0], ...
// b will be the second: : array[0][1], array[1][1], ...
}
Demo:
let array = [[1, 0], [3, 3], [2, 1], [0, 8]];
for(let [a, b] of array) {
console.log("a: " + a);
console.log("b: " + b);
}
Using a debugger within your loop would be a good way to watch and understand each step of the loop
Using the forEach method would be a clearer approach to loop through the array and its children
const items = [[1, 0],[3, 3],[2, 1],[0, 8]]
let results = {}
items.forEach((item, index) => {
// debugger;
item.forEach((subItem, subIndex) => {
// debugger;
if (results[subIndex]) {
results[subIndex] = results[subIndex] + subItem
} else {
results[subIndex] = subItem
}
})
})
console.log(results) // { 0: 6, 1: 12 }
// *********EXPLANATION BELOW ************
const items = [[1, 0],[3, 3],[2, 1],[0, 8]]
// store results in its own key:value pair
const results = {}
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach
// forEach is a more readable way to loop through an array
items.forEach((item, index) => {
// use console.log(item, index) to see the values in each loop e.g first loop contains `item = [1,0]`
// you can also use a debugger here which would be the easiest way to understand the iteration
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/debugger
// debugger;
// loop over item (e.g [1,0]) to get subItems and their index
item.forEach((subItem, subIndex) => {
// get the result from previous sums from `result`
// and add them to the current subItem values
// if there was no previous sum(i.e for first entry)
// use subItem as the first value.
if (results[subIndex]) {
results[subIndex] = results[subIndex] + subItem
} else {
results[subIndex] = subItem
}
// Below is a oneliner way to do line 16 to 20 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Conditional_Operator
// results[subIndex] = results[subIndex] ? results[subIndex] + subItem : subItem
})
})
console.log(results) // { 0: 6, 1: 12 } the results of `array[0][0],array[1][0]...` are in 0 and the result of `array[0][1], array[1][1]...` are in 1 and so on.
Obligatory one-liner to bake your noodle.
console.log([[1, 0], [3, 3], [2, 1], [0, 8]].reduce((p, c) => [p[0] += c[0], p[1] += c[1]]));
This question already has answers here:
Counting the occurrences / frequency of array elements
(39 answers)
Closed 4 years ago.
Hello I want to ask how to find same number or string on array
The output must be a number or string
Example
var arr = [1,2,4,4,5,1,1,1,8,9]
Do we need to use loop , function?
You can create a frequency array. Admittedly this might not be the most efficient way.
You can use dictionaries for this. I hope you know what dictionaries are.
function fun(arr) {
var sval;
var dict = new Object();
for (var val in arr) {
sval = string(val)
if(dict[sval] === undefined) {
dict[sval] = 1;
}
else {
dict[sval]++;
}
}
var max_count = -5;
var max_count_num;
for (var key in dict) {
if (max_count < dict[key]) {
max_count = dict[key];
max_count_num = Number(key);
}
}
}
First you create an Object, which is for our purposes serves as a dictionary, then you iterate through the array. If the key is not found, hence undefined, then we create such entry, else we increment the value which is the count by 1.
We then loop through the dictionary trying to find the number with the maximum value, hence the maximum count.
I hope this is what you are looking for.
Please fix any errors in my code, I'm a bit rusty on JavaScript.
Iterate for each item on the array (i index), and iterate for each item for the rest of the array (j index, j = i+1), and create a count to any repetition of current item.
function maxRepeated(arr) {
// count global to keep the max value count
const maxRepeat = {
value: 0,
times: 0
};
for (var i = 0; i < arr.length - 1; i++) {
var maxLocal = 1; // to count ar[i] item repetitions
for (var j = i + 1; j < arr.length; j++) {
if (arr[j] == arr[i]) maxLocal++;
console.log( maxLocal )
console.log( "I " + i + " arr[i] " + arr[i] )
}
// check if maxLocal is great than max global
if (maxLocal > maxRepeat.times) {
maxRepeat.value = arr[i];
maxRepeat.times = maxLocal;
}
}
return maxRepeat;
}
const ar = [1, 2, 3, 1, 3, 5, 1, 1, 1, 5, 4, 3, 3, 2, 2, 3];
const b = ["LUNA", "LUNA", "JS", "JS", "JS"];
//console.log(maxRepeated(ar))
console.log(maxRepeated(b))
I trying to loop through an array of arrays, and compare the elements with each-other in-order to find the common elements. so lets say if we have var arr = [[1,2,3],[4,2,5]]; I want to first compare [i][i] and [i+1][i], [i][i+1] and [i+1][i+1] and [i][i+2] and [i+1][i+2] and so on. here is my code:
function sym(args) {
var fullArr = [];
var finalArr = [];
// store the arguments inside a single array
for (var count = 0; count < arguments.length; count ++) {
fullArr[count] = arguments[count];
}
// loop through finalArr[];
for (var i = 0; i < fullArr.length; i++) {
if (fullArr[i][i] == fullArr[i++][i++]) {
// if the element matches (it is a common element)
// store it inside finalArr
finalArr[i] = fullArr[i];
}
}
return finalArr;
}
sym([1, 2, 3], [5, 2, 1, 4]);
problem: when I run the code instead of an array containing the matching element, I get an empty array
You first have to iterate over one array and see if the other array includes the value you have specified.
My answer is similar to a nested for loop in that the includes method does exactly that. It takes in as a parameter an element and checks if the array which called it contains said element. In order to do that it must iterate through all elements in the array in the worst case.
My answer also assumes that you only want to count duplicate matches once.
function sym(args) {
var fullArr = [];
var finalArr = [];
// store the arguments inside a single array
for (var count = 0; count < arguments.length; count ++) {
fullArr[count] = arguments[count];
}
// loop through finalArr[];
//since you are comparing only two arrays in this
//example you just have to iterate over each element in the first array aka fullArr[0] and
//check if each element "e" is also in the second array aka fullArr[1]
//AND that your final output array does not already contain it.
//If both of these are true then we push the element to the output array.
fullArr[0].forEach(function(e){
if(fullArr[1].includes(e) && !finalArr.includes(e)) finalArr.push(e);
});
return finalArr;
}
sym([1, 2, 3], [5, 2, 1, 4]);
However if you want to check if a particular element exists in all collections of an n length array then I would propose something like this:
function sym(args) {
var fullArr = [];
var finalArr = [];
// store the arguments inside a single array
for (var count = 0; count < arguments.length; count ++) {
fullArr[count] = arguments[count];
}
var newArr = fullArr[0].reduce( function(prev, e1) {
if(prev.indexOf(e1) < 0 && fullArr.every( function(arr){
return arr.indexOf(e1) > -1;
})){
return [...prev, e1];
}else{
return prev;
};
},[]);
alert(newArr);
return newArr;
}
sym([1,1, 2, 3,4], [5, 2, 1, 4], [4,1,2, 5]);
You can iterate over the first array and check if any of its values are common through all the other arrays.
function sym() {
var common = [];
for (var i=0; i<arguments[0].length; i++) {
var isCommon = common.indexOf(arguments[0][i]) === -1; // first check if its not already exists in the common array
for (var j=1; j<arguments.length && isCommon; j++) {
isCommon = arguments[j].indexOf(arguments[0][i]) > -1
}
if (isCommon) common.push(arguments[0][i])
}
return common;
}
of course you can improve it by iterating over the smallest array.
In your code, when the following line executes, you also increment the value of i which is your control variable:
if (fullArr[i][i] == fullArr[i++][i++])
Thus, this is how your i variable gets incremented in each iteration:
Iteration #1: i = 0
Iteration #2: i = 3
- you get i+2 from the line that I mentioned above, +1 more from the increment that you specify in the final condition of the for loop
Therefore, even after the first iteration, your function will return an empty array on your particular scenario, as you are passing an array of length 3, and the for loop ends after i = 0 on the first iteration.
Even if the loop would go on, it would return an index out of bounds exception because your array of length 3 would not have an array[3] element.
For example, if you want to compare just two arrays, as in your scenario, you need to loop through each of them and compare their elements:
function sym(array1, array2) {
var results = [];
for (var i = 0; i < array1.length; i++) {
for (var j = 0; j < array2.length; j++) {
if(array1[i] === array2[j]) {
if(results.indexOf(array1[i]) === -1) {
results.push(array1[i]);
}
}
}
}
return results;
}
sym([1, 2, 3], [5, 2, 1, 4]);
I have also built a solution that returns the intersection of the arrays that you provide as the parameters for the function, regardless of how many arrays there are:
function sym(args) {
var paramSet = Array.prototype.slice.call(arguments);
var counterObject = {};
var results = [];
paramSet.forEach(function (array) {
// Filter the arrays in order to remove duplicate values
var uniqueArray = array.filter(function (elem, index, arr) {
return index == arr.indexOf(elem);
});
uniqueArray.forEach(function (element) {
if (Object.prototype.hasOwnProperty.call(counterObject, element)) {
counterObject[element]++;
} else {
counterObject[element] = 1;
}
});
});
for (var key in counterObject) {
if (counterObject[key] === paramSet.length) {
results.push(parseInt(key));
}
}
return results;
}
sym([1, 2, 3, 3, 3], [5, 2, 1, 4], [1, 7, 9, 10]);
The above code will return [1] for the example that I provided, as that is the intersection of all 3 arrays.
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);
}
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))