I am trying to make a removeAll() function, which will remove all elements of an array with that particular value (not index).
The tricky part comes when we make any change to the loop, the indexes tend to move around (making it very hard to make it work like we want) and, restarting the loop every time we make changes is very inefficient on big arrays.
So far, I wrote my own arr.indexOf function (for older IE support), it looks like this:
function arrFind(val, arr) {
for (var i = 0, len = arr.length, rtn = -1; i < len; i++) {
if (arr[i] === val) {
return i;
}
}
return -1;
}
It is easy to remove elements like this:
var myarray = [0, 1, 2, 3, 4];
var tofind = 2;
var stored_index = arrFind(tofind, myarray);
if (stored_index != -1) {
myarray.splice(stored_index, 1);
}
alert(myarray.join(",")); //0,1,3,4
However, as I pointed out earlier, when doing this while looping, we get in trouble.
Any ideas on how to properly remove array items while looping through it?
Loop in reverse order or build a new array with the items that are not to be removed.
Every new browser has an Array filter method:
var myarray=[0,1,2,3,4];
var removal=2;
var newarray=myarray.filter(function(itm){return itm!==removal});
Try this one. You just have to check the indices of the numbers you would like to remove. I have added additional elements in your array.
var myarray = [0, 1, 2, 3, 2, 2, 2, 5, 6];
var indicesToRemove = new Array();
for(i=0;i<myarray.length;i++){
if(myarray[i]===2){ //let's say u wud like to remove all 2
indicesToRemove.push(i); //getting the indices and pushing it in a new array
}
}
for (var j = indicesToRemove.length -1; j >= 0; j--){
myarray.splice(indicesToRemove[j],1);
}
alert(JSON.stringify(myarray)); //myarray will be [0,1,3,5,6]
I wrote this little function where arr is the original array and d1, d2 the values you want removed. I wonder how it could be generalized to an arbitrary number of values to be removed. Well, I'm just a beginner.
function destroyer(arr, d1, d2) {
var lean =[];
for (var i = 0; i<arr.length; i++) {
if (arr[i] != d1 && arr[i] != d2) {
lean.push(arr[i]);
}
}
return lean;
Related
I've been trying the Number.isInteger() method on chrome console.
and after doing a for loop and checking the result with the console.log(arr); I'm getting an array with only one value of 1. like this [1];
var arr = [1,2,3,'some','string'];
for (var i = 0; i < arr.length; i++) {
if (Number.isInteger(arr[i])) {
arr.splice(arr.indexOf(arr[i], 1));
}
}
Any one have an idea, if I'm doing it wrong or something. thanks for help.
You have a major problem, you are continually removing items from the array while looping through it. You have to go back one step (i--) every time an item is removed.
var arr = [1,2,3,'some','string'];
for (var i = 0; i < arr.length; i++) {
if (!isNaN(arr[i])) { // isNaN return true if it's not a valid number, so we have to inverse the test
arr.splice(i, 1); // if it's a valid number remove the element at the index i (no need to search for the index using indexOf, we already have it its i)
i--; // if we remove an element, we have to go back one step (or we will leave one item behind every time we remove another)
}
}
console.log(arr);
You could use typeof instead:
var arr = [1,2,3,'some','string'];
for (var i = 0; i < arr.length; i++) {
if (typeof arr[i] == 'number') {
arr.splice(arr.indexOf(arr[i], 1));
}
}
The `.splice()' method makes changes to the array itself.
So for each iteration of the array, you are changing it fundamentally.
If you want the array to include only integers:
var arr = [1,2,3,'some','string'];
var newArray = [];
arr.forEach(function(element) {
if (Number.isInteger(element)){
newArray.push(element);
}
});
console.log(newArray);
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);
}
I have an array and an array of objects. I want to search each value in the array in the array of objects and if it doesnt exist, I want to remove the value from the array.
var arr= [1,2,3,4];
var recs = [{id:1},{id:2},{id:3}]; //4 doesnt exist in recs, remove from arr
//arr = [1,2,3];
Heres my attempt. Obviously does not work. I am not sure how I can compare each arr index with all the values in recs before moving on the next arr index:
var arr= [1, 2, 3, 4], index;
var recs = [{a:1},{a:2},{a:3}];
for(var i = 0; i<arr.length; i++){
for(var val in recs[i]){
if(arr[i] != recs[i][val]){
index = arr.indexOf(arr[i]);
arr.splice(index, 1);
}
}
}
thank you!!
If you are okay with leaving your original array instance alone and creating a new one (essentially treating it as immutable)
var newArr = arr.filter(function(num) {
return !recs.every(function(obj) {
return obj.a !== num;
});
});
Detail of the methods used: Array.filter is passed a function, runs that function on each element inside, and then returns a new array with only the elements that returned true in the function.
Array.every works a little similar, but returns a Boolean, true or false. It returns true if all of the elements of the array returned true inside of the function.
var arr= [1, 2, 3, 4];
var recs = [{a:1},{a:2},{a:3}];
// don't use var in for loops.
// Variables declared with var have function scope, so declare them at the top of your function
var i;
var j;
var value;
var found;
// iterate over the array
for (i = 0; i < arr.length; i++)
{
value = arr[i];
found = false;
// iterate over the other array
for (j = 0 ; j < recs.length ; j++)
{
// if we found what we were looking for, make a note and exit loop
if (recs[j].a == value)
{
found = true;
break;
}
}
if (!found)
{
arr.splice(i, 1);
// To compensate the loop's i++, to avoid skipping the next entry
i--;
}
}
alert(arr.join(','));
How can I remove an object from a copy of an array without removing it from the original?
I have a global variable :
var userTrickList = [];
And inside a function, I make a copy of that global array :
var tempUserTrickList = userTrickList;
Then I use the removeItem function that I created to remove a certain object.
removeItem(considerTrick.IDName, tempUserTrickList);
function removeItem(item, list) {
//takes a string as 'item', finds in the array as 'list',
//then removes it from the list.
for(var i = 0; i < list.length; i++)
{
if(item === list[i])
{
list.splice(i,1);
}
}
}
My problem is, this function removes it from the userTrickList too.
Any ideas? It's definitely a problem in "removeItem(considerTrick.IDName, tempUserTrickList);", but I can't think of a solution.
Use .slice(0) to clone an array.
var tempUserTrickList = userTrickList.slice(0);
Credits:
http://davidwalsh.name/javascript-clone-array
use this function for your requirement
function removeElementFromArray(data,target) {
var temp=new Array();
for ( var i = 0; i < data.length; i++) {
if(data[i]!=target){
temp.push(data[i]);
}
}
return temp; }
here data is original array and target is the element you want to remove from array
this function will return array without containing the removed item.
Try, It copy the original array
var tempUserTrickList = JSON.parse(JSON.stringify(userTrickList));
Demo CopyArray
for (i = 0, l = arr.length; i < l; i++) {
if (arr[i] === item) {
arr.splice(i, 1);
i -= 1;
l -= 1;
}
}
Daniel's method of cloning an array is absolutely correct, but since I don't see an ES6-oriented answer, I'll offer up an alternative solution:
We can just as easily use the spread operator to clone an array, so we don't have to use the slice call.
const arr = [1, 2, 3];
const copy = [...arr];
copy.pop();
console.log(arr); // returns [1, 2, 3]
console.log(copy); // returns [1, 2]
i have a java script array object and i want to delete items from a specific index in that object, i have a comma separated string of that indexes. problem is that when i delete it using splice array indexes got changed, and other indexes's object not got deleted.
var DeletedConditions="3, 5, 19, 50";
for (var k = 0; k < DeletedConditions.split(", ").length; k++) {
ConditionObject.splice(DeletedConditions.split(", ")[k], 1);
}
DeletedConditions string can be anything.
please help me out. how to get this done.
First of all, I suggest you officially turn the indexes into a formal array. Having a string as an index reference, you are prone to missing a split shall there be a case where the values are not separated by ,
Then the code:
var content = ['foo', 'bar', 'baz', 'bam', 'dom', 'zok'],
deleteIndexes = [5, 1, 3],//should delete zok, bar, bam
i;
//sort from least to greatest: [1, 3, 5]
deleteIndexes.sort(function(a, b) {
return a - b;
});
//we loop backwards (performance enhancement)
//now we loop from greatest to least
//we now splice from greatest to least
//to avoid altering the indexes of the content as we splice
for (i = deleteIndexes.length; i-- > 0;) {
content.splice(deleteIndexes[i],1);
}
console.log(content); //["foo", "baz", "dom"]
You can always decrement the k iterator after splicing inside the loop:
k--;
var DeletedConditions="3, 5, 19, 50";
var list = DeletedConditions.split(", ")
for (var k = 0; k < list.length; k++) {
// using splice here
list.splice(k,1);
k--;
}
console.log(list.join(', '))
Removing an item from the beginning of the array shuffles the later elements up and changes their indices, as you've observed. But if you go through the list of items to remove backwards then it will remove the later elements first so the indices will still be correct for the elements closer to the beginning of the array.
Also, please don't do the .split() operation on every loop iteration - the inefficiency might not make much difference on a string with four numbers in it, but it makes the code kind of messy and on principle it is just kind of yucky.
var DeletedConditions="3, 5, 19, 50",
delCondArr = DeletedConditions.split();
for (var k = delCondArr.length - 1; k >= 0; k--) {
ConditionObject.splice(delCondArr[k], 1);
}
If there's a possibility that the DeletedConditions strig might not be ordered just add a .sort() after you split it:
delCondArr = DeletedConditions.split().sort(function(a,b){return a-b;});
...in which case you don't need to loop backwards.
It might be easiest to copy the original array, omitting the deleted items in the process. Something like this would do the trick...
var DeletedConditions="3, 5, 19, 50";
DeletedConditions = DeletedConditions.split(', ');
var newConditionObject = [];
for(var k = 0; k < ConditionObject.length; ++k) {
if(DeletedConditions.indexOf(k) !== -1) { continue; }
newConditionObject.push(ConditionObject[k]);
}
// result is in `newConditionObject`
console.log(newConditionObject);
var fruits = new Array("apple", "banana", "grapes", "oranges","mosambi","aaa","bbb","ccc");
var DeletedConditions="1,3,4,5";
var indexArray = new Array;
indexArray = DeletedConditions.split(",");
for (var i = 0; i < indexArray.length; i++) {
fruits.splice(indexArray[i], 1);
}