I have:
var array = new Array();
array.push("A");
array.push("B");
array.push("C");
I want to be able to do something like:
array.remove("B");
but there is no remove function. How do I accomplish this?
I'm actually updating this thread with a more recent 1-line solution:
let arr = ['A', 'B', 'C'];
arr = arr.filter(e => e !== 'B'); // will return ['A', 'C']
The idea is basically to filter the array by selecting all elements different to the element you want to remove.
Note: will remove all occurrences.
EDIT:
If you want to remove only the first occurence:
t = ['A', 'B', 'C', 'B'];
t.splice(t.indexOf('B'), 1); // will return ['B'] and t is now equal to ['A', 'C', 'B']
Loop through the list in reverse order, and use the .splice method.
var array = ['A', 'B', 'C']; // Test
var search_term = 'B';
for (var i=array.length-1; i>=0; i--) {
if (array[i] === search_term) {
array.splice(i, 1);
// break; //<-- Uncomment if only the first term has to be removed
}
}
The reverse order is important when all occurrences of the search term has to be removed. Otherwise, the counter will increase, and you will skip elements.
When only the first occurrence has to be removed, the following will also work:
var index = array.indexOf(search_term); // <-- Not supported in <IE9
if (index !== -1) {
array.splice(index, 1);
}
List of One Liners
Let's solve this problem for this array:
var array = ['A', 'B', 'C'];
1. Remove only the first:
Use If you are sure that the item exist
array.splice(array.indexOf('B'), 1);
2. Remove only the last:
Use If you are sure that the item exist
array.splice(array.lastIndexOf('B'), 1);
3. Remove all occurrences:
array = array.filter(v => v !== 'B');
DEMO
You need to find the location of what you're looking for with .indexOf() then remove it with .splice()
function remove(arr, what) {
var found = arr.indexOf(what);
while (found !== -1) {
arr.splice(found, 1);
found = arr.indexOf(what);
}
}
var array = new Array();
array.push("A");
array.push("B");
array.push("C");
remove(array, 'B');
alert(array);
This will take care of all occurrences.
Simply
array.splice(array.indexOf(item), 1);
Simple solution (ES6)
If you don't have duplicate element
Array.prototype.remove = function(elem) {
var indexElement = this.findIndex(el => el === elem);
if (indexElement != -1)
this.splice(indexElement, 1);
return this;
};
Online demo (fiddle)
const changedArray = array.filter( function(value) {
return value !== 'B'
});
or you can use :
const changedArray = array.filter( (value) => value === 'B');
The changedArray will contain the without value 'B'
In case of wanting to remove array of strings from array of strings:
const names = ['1','2','3','4']
const excludeNames = ['2','3']
const filteredNames = names.filter((name) => !excludeNames.includes(name));
// ['1','4']
You have to write you own remove. You can loop over the array, grab the index of the item you want to remove, and use splice to remove it.
Alternatively, you can create a new array, loop over the current array, and if the current object doesn't match what you want to remove, put it in a new array.
use:
array.splice(2, 1);
This removes one item from the array, starting at index 2 (3rd item)
use array.splice
/*array.splice(index , howMany[, element1[, ...[, elementN]]])
array.splice(index) // SpiderMonkey/Firefox extension*/
array.splice(1,1)
Source:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice
This only valid on str list, look up this
myStrList.filter(item=> !["deletedValue","deletedValue2"].includes(item))
Here is the simplest answer.
First find index using indexofand then
if index exist use splice
const array = ['apple', 'banana', 'orange', 'pear'];
const index = array.indexOf('orange'); // Find the index of the element to remove
if (index !== -1) { // Make sure the element exists in the array
array.splice(index, 1); // Remove the element at the found index
}
console.log(array); // ["apple", "banana", "pear"]
Related
I have two arrays and the idea is to find text in first array and replace itwith the value of second array ( Same index ).
Example
Text to search & replace: Visina
var array1 = ['Visina','Tezina'];
var array2 = ['Height','Weight'];
So the script should search for "Visina" in first array, find the index and replace with the value from second array with same index.
Also, it needs to toggle.
Well, you simply should use Array.indexOf() method:
var array1 = ['Visina', 'Tezina'];
var array2 = ['Height', 'Weight'];
function swap(str) {
const index = array1.indexOf(str);
if (index !== -1) {
array1[index] = array2[index];
array2[index] = str;
}
}
swap('Visina');
console.log(array1);
console.log(array2);
var arr = [30];
delete arr[0];
if (arr.length == 0) {
alert("empty");
}
This code won't work only because of delete.
Is there an ultimate way to check if the array is empty no matter what?
Thanks :)
You can use Object.values() to get actual values from the array. If the length of the values array is 0, then the array is empty by your definition.
const checkIfSparseIsEmpty = arr => !Object.values(arr).length
var arr1 = [30];
delete arr1[0];
console.log(checkIfSparseIsEmpty(arr1)) // true
var arr2 = [1, 2, 3]
delete arr2[0]
delete arr2[1]
console.log(checkIfSparseIsEmpty(arr2)) // false
console.log(checkIfSparseIsEmpty(Array(10))) // true
The reason behind the expected behaviour is that when you use the delete operator, it replaces the element by undefined, and since the length doesn't change the above check does not work.
One of the ways to effectively delete an element from the array is to use the filer array function.
Example:
function deleter(arr, toDelete) {
let newArray = arr.filter((ar) => {
return ar !== toDelete;
})
return newArray;
}
let array = [1,2,3,4,5]
console.log(deleter(array, 5));
Now to check if an element exists in an array, you can use the indexOf method available on the array prototype.
Following is an example:
function deleter(arr, toDelete) {
let newArray = arr.filter((ar) => {
return ar !== toDelete;
})
return newArray;
}
let array = [1,2,3,4,5]
let toDelete = 5;
let newArr = deleter(array, toDelete);
console.log(newArr.indexOf(toDelete))
// -1 corresponds to the element not found.
I need to check each element of an array for a certain letter. if the element contains this letter it should stay within the array, if it does not it should be removed.
currently I'm able to remove elements if they are exact, but not sure how to go about checking each index of each element.
var exampleList = ['alpha', 'beta','dog']
exampleList.filter(function(word) {
return (word == 'dog');
})
my end goal would be something like this.
letterToInclude = 'a'
var exampleList = ['alpha', 'beta','dog', 'mouse']
exampleList.filter(function(word) {
return (word == letterToInclude);
})
// returned values = ['alpha', 'beta']
Instead of doing ==, you can use indexOf to see if letterToInclude occurs in word.
letterToInclude = 'a'
var exampleList = ['alpha', 'beta','dog', 'mouse']
exampleList.filter(function(word) {
return (word.indexOf(letterToInclude) > -1);
});
indexOf returns the position that letterToInclude occurs in word; in the event it is not found, indexOf will return -1.
The reason I didn't use word.includes(letterToInclude) is just for compatibility purposes. includes is fairly new and isn't completely supported.
You can use indexOf() to check if each element contains a specific letter.
var letterToInclude = 'a'
var exampleList = ['alpha', 'beta', 'dog', 'mouse']
exampleList = exampleList.filter(function(word) {
return word.indexOf(letterToInclude) != -1
})
console.log(exampleList)
ES6 solution with String#includes(), also you can use match() or test() but those take regular expressions.
exampleList.filter(word => word.includes(letterToInclude))
Try using indexOf:
letterToInclude = 'a'
var exampleList = ['alpha', 'beta','dog', 'mouse']
console.log(exampleList.filter(function(word) {
return ~(word.indexOf(letterToInclude));
}));
It works well together with Unicode chars:
var lettersToInclude = 'aa'
var exampleList = ['a', 'aa','❤✓☀a★bAb', 'bbaa', 'aa☂']
var r = exampleList.filter(function(word) {
return (word.indexOf(lettersToInclude) > -1);
});
console.log(r);
I use lodash to insert an item into an array if it's not there, and remove it if it exists, kind of "toggling".
My code looks like this:
var items = ['a', 'b', 'c'];
var itemToToggle = 'a';
if (_.includes(items, itemToToggle)) {
_.pull(items, itemToToggle)
}
else {
items.push(itemToToggle)
}
Which seems not perfect enough.
Can I simplify it to, ideally, have something like _.toggle(items, itemToToggle)?
Another way to do it would be to use lodash's xor
var items = ['a', 'b', 'c'];
var itemToToggle = 'a';
new_array = _.xor(items, [itemToToggle])
return new_array // ['b', 'c']
Which will add the item if it does not exist, and remove if it does.
It does this by comparing the two arrays (items and [itemToToggle]) and returning a new array that is a merge of the two arrays, minus duplicates.
Your code seems fine to me. The only thing, I can think of is using the length to see if an item was removed, and if not, add it:
function toggleValueInArr(arr, value) {
var originalLength = arr.length; // cache the original length
_.pull(arr, value).length === originalLength && arr.push(value); // check if the length is the same as the original - ie no item was not removed. If so, push it.
return arr;
}
I have this code which is supposed to iterate over each item in an array, removing items based on some condition:
//iterate over all items in an array
//if the item is "b", remove it.
var array = ["a", "b", "c"];
array.forEach(function(item) {
if(item === "b") {
array.splice(array.indexOf(item), 1);
}
console.log(item);
});
Desired output:
a
b
c
Actual output:
a
b
Obviously the native forEach method doesn't check after each iteration whether the item has been deleted, so if it is then the next item is skipped. Is there a better way of doing this, aside from overriding the forEach method or implementing my own class to use instead of an array?
Edit - further to my comment, I suppose the solution is to just use a standard for loop. Feel free to answer if you have a better way.
Lets see why JavaScript behaves like this. According to the ECMAScript standard specification for Array.prototype.forEach,
when you delete an element at index 1, the element at index 2 becomes the element at index 1 and index 2 doesn't exist for that object.
Now, JavaScript looks for element 2 in the object, which is not found, so it skips the function call.
That is why you see only a and b.
The actual way to do this, is to use Array.prototype.filter
var array = ["a", "b", "c"];
array = array.filter(function(currentChar) {
console.log(currentChar); // a, b, c on separate lines
return currentChar !== "b";
});
console.log(array); // [ 'a', 'c' ]
One possibility would be to use the array.slice(0) function, which creates a copy (clone) of the array and thus the iteration is separated from the deletion.
Then the only change to the original approach using array.forEach would be to change it to array.slice(0).forEach and it will work:
array.slice(0).forEach(function(item) {
if(item === "b") {
array.splice(array.indexOf(item), 1);
}
alert(item)
});
After the forEach, the array will contain only a and c.
A jsFiddle demo can be found here.
Using Array.prototype.filter as in thefourtheye's answer is a good way to go, but this could also be done with a while loop. E.g.:
const array = ["a", "b", "c"];
let i = 0;
while (i < array.length) {
const item = array[i];
if (item === "b") {
array.splice(i, 1);
} else {
i += 1;
}
console.log(item);
}
Another possibility would be to use the array.reduceRight function to avoid the skip:
//iterate over all items in an array from right to left
//if the item is "b", remove it.
const array = ["a", "b", "c"];
array.reduceRight((_, item, i) => {
if(item === "b") {
array.splice(i, 1);
}
}, null);
console.log(array);
After the reduceRight, the array will contain only a and c.