Remove duplicates in Select Angular JS 2.x [duplicate] - json
I need to check a JavaScript array to see if there are any duplicate values. What's the easiest way to do this? I just need to find what the duplicated values are - I don't actually need their indexes or how many times they are duplicated.
I know I can loop through the array and check all the other values for a match, but it seems like there should be an easier way.
Similar question:
Get all unique values in a JavaScript array (remove duplicates)
You could sort the array and then run through it and then see if the next (or previous) index is the same as the current. Assuming your sort algorithm is good, this should be less than O(n2):
const findDuplicates = (arr) => {
let sorted_arr = arr.slice().sort(); // You can define the comparing function here.
// JS by default uses a crappy string compare.
// (we use slice to clone the array so the
// original array won't be modified)
let results = [];
for (let i = 0; i < sorted_arr.length - 1; i++) {
if (sorted_arr[i + 1] == sorted_arr[i]) {
results.push(sorted_arr[i]);
}
}
return results;
}
let duplicatedArray = [9, 9, 111, 2, 3, 4, 4, 5, 7];
console.log(`The duplicates in ${duplicatedArray} are ${findDuplicates(duplicatedArray)}`);
In case, if you are to return as a function for duplicates. This is for similar type of case.
Reference: https://stackoverflow.com/a/57532964/8119511
If you want to elimate the duplicates, try this great solution:
function eliminateDuplicates(arr) {
var i,
len = arr.length,
out = [],
obj = {};
for (i = 0; i < len; i++) {
obj[arr[i]] = 0;
}
for (i in obj) {
out.push(i);
}
return out;
}
console.log(eliminateDuplicates([1,6,7,3,6,8,1,3,4,5,1,7,2,6]))
Source:
http://dreaminginjavascript.wordpress.com/2008/08/22/eliminating-duplicates/
This is my answer from the duplicate thread (!):
When writing this entry 2014 - all examples were for-loops or jQuery. JavaScript has the perfect tools for this: sort, map and reduce.
Find duplicate items
var names = ['Mike', 'Matt', 'Nancy', 'Adam', 'Jenny', 'Nancy', 'Carl']
const uniq = names
.map((name) => {
return {
count: 1,
name: name
};
})
.reduce((result, b) => {
result[b.name] = (result[b.name] || 0) + b.count;
return result;
}, {});
const duplicates = Object.keys(uniq).filter((a) => uniq[a] > 1);
console.log(duplicates); // [ 'Nancy' ]
More functional syntax:
#Dmytro-Laptin pointed out some code that can be removed. This is a more compact version of the same code. Using some ES6 tricks and higher-order functions:
const names = ['Mike', 'Matt', 'Nancy', 'Adam', 'Jenny', 'Nancy', 'Carl'];
const count = names =>
names.reduce((result, value) => ({ ...result,
[value]: (result[value] || 0) + 1
}), {}); // don't forget to initialize the accumulator
const duplicates = dict =>
Object.keys(dict).filter((a) => dict[a] > 1);
console.log(count(names)); // { Mike: 1, Matt: 1, Nancy: 2, Adam: 1, Jenny: 1, Carl: 1 }
console.log(duplicates(count(names))); // [ 'Nancy' ]
UPDATED: Short one-liner to get the duplicates:
[1, 2, 2, 4, 3, 4].filter((e, i, a) => a.indexOf(e) !== i) // [2, 4]
To get the array without duplicates simply invert the condition:
[1, 2, 2, 4, 3, 4].filter((e, i, a) => a.indexOf(e) === i) // [1, 2, 3, 4]
Note that this answer’s main goal is to be short. If you need something performant for a big array, one possible solution is to sort your array first (if it is sortable) then do the following to get the same kind of results as above:
myHugeSortedArray.filter((e, i, a) => a[i-1] === e)
Here is an example for a 1 000 000 integers array:
const myHugeIntArrayWithDuplicates =
[...Array(1_000_000).keys()]
// adding two 0 and four 9 duplicates
.fill(0, 2, 4).fill(9, 10, 14)
console.time("time")
console.log(
myHugeIntArrayWithDuplicates
// a possible sorting method for integers
.sort((a, b) => a > b ? 1 : -1)
.filter((e, i, a) => a[i-1] === e)
)
console.timeEnd("time")
On my AMD Ryzen 7 5700G dev machine it outputs:
[ 0, 0, 9, 9, 9, 9 ]
time: 22.738ms
As pointed out in the comments both the short solution and the performant solution will return an array with several time the same duplicate if it occurs more than once in the original array:
[1, 1, 1, 2, 2, 2, 2].filter((e, i, a) => a.indexOf(e) !== i) // [1, 1, 2, 2, 2]
If unique duplicates are wanted then a function like
function duplicates(arr) {
return [...new Set(arr.filter((e, i, a) => a.indexOf(e) !== i))]
}
can be used so that duplicates([1, 1, 1, 2, 2, 2, 2]) returns [1, 2].
When all you need is to check that there are no duplicates as asked in this question you can use the every() method:
[1, 2, 3].every((e, i, a) => a.indexOf(e) === i) // true
[1, 2, 1].every((e, i, a) => a.indexOf(e) === i) // false
Note that every() doesn't work for IE 8 and below.
Find duplicate values in an array
This should be one of the shortest ways to actually find duplicate values in an array. As specifically asked for by the OP, this does not remove duplicates but finds them.
var input = [1, 2, 3, 1, 3, 1];
var duplicates = input.reduce(function(acc, el, i, arr) {
if (arr.indexOf(el) !== i && acc.indexOf(el) < 0) acc.push(el); return acc;
}, []);
document.write(duplicates); // = 1,3 (actual array == [1, 3])
This doesn't need sorting or any third party framework. It also doesn't need manual loops. It works with every value indexOf() (or to be clearer: the strict comparision operator) supports.
Because of reduce() and indexOf() it needs at least IE 9.
You can add this function, or tweak it and add it to Javascript's Array prototype:
Array.prototype.unique = function () {
var r = new Array();
o:for(var i = 0, n = this.length; i < n; i++)
{
for(var x = 0, y = r.length; x < y; x++)
{
if(r[x]==this[i])
{
alert('this is a DUPE!');
continue o;
}
}
r[r.length] = this[i];
}
return r;
}
var arr = [1,2,2,3,3,4,5,6,2,3,7,8,5,9];
var unique = arr.unique();
alert(unique);
UPDATED: The following uses an optimized combined strategy. It optimizes primitive lookups to benefit from hash O(1) lookup time (running unique on an array of primitives is O(n)). Object lookups are optimized by tagging objects with a unique id while iterating through so so identifying duplicate objects is also O(1) per item and O(n) for the whole list. The only exception is items that are frozen, but those are rare and a fallback is provided using an array and indexOf.
var unique = function(){
var hasOwn = {}.hasOwnProperty,
toString = {}.toString,
uids = {};
function uid(){
var key = Math.random().toString(36).slice(2);
return key in uids ? uid() : uids[key] = key;
}
function unique(array){
var strings = {}, numbers = {}, others = {},
tagged = [], failed = [],
count = 0, i = array.length,
item, type;
var id = uid();
while (i--) {
item = array[i];
type = typeof item;
if (item == null || type !== 'object' && type !== 'function') {
// primitive
switch (type) {
case 'string': strings[item] = true; break;
case 'number': numbers[item] = true; break;
default: others[item] = item; break;
}
} else {
// object
if (!hasOwn.call(item, id)) {
try {
item[id] = true;
tagged[count++] = item;
} catch (e){
if (failed.indexOf(item) === -1)
failed[failed.length] = item;
}
}
}
}
// remove the tags
while (count--)
delete tagged[count][id];
tagged = tagged.concat(failed);
count = tagged.length;
// append primitives to results
for (i in strings)
if (hasOwn.call(strings, i))
tagged[count++] = i;
for (i in numbers)
if (hasOwn.call(numbers, i))
tagged[count++] = +i;
for (i in others)
if (hasOwn.call(others, i))
tagged[count++] = others[i];
return tagged;
}
return unique;
}();
If you have ES6 Collections available, then there is a much simpler and significantly faster version. (shim for IE9+ and other browsers here: https://github.com/Benvie/ES6-Harmony-Collections-Shim)
function unique(array){
var seen = new Set;
return array.filter(function(item){
if (!seen.has(item)) {
seen.add(item);
return true;
}
});
}
var a = ["a","a","b","c","c"];
a.filter(function(value,index,self){ return (self.indexOf(value) !== index )})
This should get you what you want, Just the duplicates.
function find_duplicates(arr) {
var len=arr.length,
out=[],
counts={};
for (var i=0;i<len;i++) {
var item = arr[i];
counts[item] = counts[item] >= 1 ? counts[item] + 1 : 1;
if (counts[item] === 2) {
out.push(item);
}
}
return out;
}
find_duplicates(['one',2,3,4,4,4,5,6,7,7,7,'pig','one']); // -> ['one',4,7] in no particular order.
Find non-unique values from 3 arrays (or more):
ES2015
// 🚩🚩 🚩 🚩 🚩
var arr = [1,2,2,3,3,4,5,6,2,3,7,8,5,22],
arr2 = [1,2,511,12,50],
arr3 = [22,0],
merged,
nonUnique;
// Combine all the arrays to a single one
merged = arr.concat(arr2, arr3)
// create a new (dirty) Array with only the non-unique items
nonUnique = merged.filter((item,i) => merged.includes(item, i+1))
// Cleanup - remove duplicate & empty items items
nonUnique = [...new Set(nonUnique)]
console.log(nonUnique)
PRE-ES2015:
In the below example I chose to superimpose a unique method on top of the Array prototype, allowing access from everywhere and has more "declarative" syntax. I do not recommend this approach on large projects, since it might very well collide with another method with the same custom name.
Array.prototype.unique = function () {
var arr = this.sort(), i=arr.length; // input must be sorted for this to work
while(i--)
arr[i] === arr[i-1] && arr.splice(i,1) // remove duplicate item
return arr
}
Array.prototype.nonunique = function () {
var arr = this.sort(), i=arr.length, res = []; // input must be sorted for this to work
while(i--)
arr[i] === arr[i-1] && (res.indexOf(arr[i]) == -1) && res.push(arr[i])
return res
}
// 🚩🚩 🚩 🚩 🚩
var arr = [1,2,2,3,3,4,5,6,2,3,7,8,5,22],
arr2 = [1,2,511,12,50],
arr3 = [22,0],
// merge all arrays & call custom Array Prototype - "unique"
unique = arr.concat(arr2, arr3).unique(),
nonunique = arr.concat(arr2, arr3).nonunique()
console.log(unique) // [1,12,2,22,3,4,5,50,511,6,7,8]
console.log(nonunique) // [1,12,2,22,3,4,5,50,511,6,7,8]
using underscore.js
function hasDuplicate(arr){
return (arr.length != _.uniq(arr).length);
}
The simplest and quickest way is to use the Set object:
const numbers = [1, 2, 3, 2, 4, 5, 5, 6];
const set = new Set(numbers);
const duplicates = numbers.filter(item => {
if (set.has(item)) {
set.delete(item);
return false;
} else {
return true;
}
});
// OR more concisely
const duplicates = numbers.filter(item => !set.delete(item));
console.log(duplicates);
// [ 2, 5 ]
This is my proposal (ES6):
let a = [1, 2, 3, 4, 2, 2, 4, 1, 5, 6]
let b = [...new Set(a.sort().filter((o, i) => o !== undefined && a[i + 1] !== undefined && o === a[i + 1]))]
// b is now [1, 2, 4]
Here's the simplest solution I could think of:
const arr = [-1, 2, 2, 2, 0, 0, 0, 500, -1, 'a', 'a', 'a']
const filtered = arr.filter((el, index) => arr.indexOf(el) !== index)
// => filtered = [ 2, 2, 0, 0, -1, 'a', 'a' ]
const duplicates = [...new Set(filtered)]
console.log(duplicates)
// => [ 2, 0, -1, 'a' ]
That's it.
Note:
It works with any numbers including 0, strings and negative numbers e.g. -1 -
Related question: Get all unique values in a JavaScript array (remove duplicates)
The original array arr is preserved (filter returns the new array instead of modifying the original)
The filtered array contains all duplicates; it can also contain more than 1 same value (e.g. our filtered array here is [ 2, 2, 0, 0, -1, 'a', 'a' ])
If you want to get only values that are duplicated (you don't want to have multiple duplicates with the same value) you can use [...new Set(filtered)] (ES6 has an object Set which can store only unique values)
Hope this helps.
Here is mine simple and one line solution.
It searches not unique elements first, then makes found array unique with the use of Set.
So we have array of duplicates in the end.
var array = [1, 2, 2, 3, 3, 4, 5, 6, 2, 3, 7, 8, 5, 22, 1, 2, 511, 12, 50, 22];
console.log([...new Set(
array.filter((value, index, self) => self.indexOf(value) !== index))]
);
Shortest vanilla JS:
[1,1,2,2,2,3].filter((v,i,a) => a.indexOf(v) !== i) // [1, 2, 2]
one liner simple way
var arr = [9,1,2,4,3,4,9]
console.log(arr.filter((ele,indx)=>indx!==arr.indexOf(ele))) //get the duplicates
console.log(arr.filter((ele,indx)=>indx===arr.indexOf(ele))) //remove the duplicates
var a = [324,3,32,5,52,2100,1,20,2,3,3,2,2,2,1,1,1].sort();
a.filter(function(v,i,o){return i&&v!==o[i-1]?v:0;});
or when added to the prototyp.chain of Array
//copy and paste: without error handling
Array.prototype.unique =
function(){return this.sort().filter(function(v,i,o){return i&&v!==o[i-1]?v:0;});}
See here: https://gist.github.com/1305056
Fast and elegant way using es6 object destructuring and reduce
It runs in O(n) (1 iteration over the array) and doesn't repeat values that appear more than 2 times
const arr = ['hi', 'hi', 'hi', 'bye', 'bye', 'asd']
const {
dup
} = arr.reduce(
(acc, curr) => {
acc.items[curr] = acc.items[curr] ? acc.items[curr] += 1 : 1
if (acc.items[curr] === 2) acc.dup.push(curr)
return acc
}, {
items: {},
dup: []
},
)
console.log(dup)
// ['hi', 'bye']
You can use filter method and indexOf() to get all the duplicate values
function duplicate(arr) {
return duplicateArray = arr.filter((item, index) => arr.indexOf(item) !== index)
}
arr.indexOf(item) will always return the first index at which a given element can be
found
ES5 only (i.e., it needs a filter() polyfill for IE8 and below):
var arrayToFilter = [ 4, 5, 5, 5, 2, 1, 3, 1, 1, 2, 1, 3 ];
arrayToFilter.
sort().
filter( function(me,i,arr){
return (i===0) || ( me !== arr[i-1] );
});
Here is a very light and easy way:
var codes = dc_1.split(',');
var i = codes.length;
while (i--) {
if (codes.indexOf(codes[i]) != i) {
codes.splice(i,1);
}
}
ES6 offers the Set data structure which is basically an array that doesn't accept duplicates.
With the Set data structure, there's a very easy way to find duplicates in an array (using only one loop).
Here's my code
function findDuplicate(arr) {
var set = new Set();
var duplicates = new Set();
for (let i = 0; i< arr.length; i++) {
var size = set.size;
set.add(arr[i]);
if (set.size === size) {
duplicates.add(arr[i]);
}
}
return duplicates;
}
With ES6 (or using Babel or Typescipt) you can simply do:
var duplicates = myArray.filter(i => myArray.filter(ii => ii === i).length > 1);
https://es6console.com/j58euhbt/
Simple code with ES6 syntax (return sorted array of duplicates):
let duplicates = a => {d=[]; a.sort((a,b) => a-b).reduce((a,b)=>{a==b&&!d.includes(a)&&d.push(a); return b}); return d};
How to use:
duplicates([1,2,3,10,10,2,3,3,10]);
I have just figured out a simple way to achieve this using an Array filter
var list = [9, 9, 111, 2, 3, 4, 4, 5, 7];
// Filter 1: to find all duplicates elements
var duplicates = list.filter(function(value,index,self) {
return self.indexOf(value) !== self.lastIndexOf(value) && self.indexOf(value) === index;
});
console.log(duplicates);
This answer might also be helpful, it leverages js reduce operator/method to remove duplicates from array.
const result = [1, 2, 2, 3, 3, 3, 3].reduce((x, y) => x.includes(y) ? x : [...x, y], []);
console.log(result);
Higher ranked answers have a few inherent issues including the use of legacy javascript, incorrect ordering or with only support for 2 duplicated items.
Here's a modern solution which fixes those problems:
const arrayNonUniq = array => {
if (!Array.isArray(array)) {
throw new TypeError("An array must be provided!")
}
return array.filter((value, index) => array.indexOf(value) === index && array.lastIndexOf(value) !== index)
}
arrayNonUniq([1, 1, 2, 3, 3])
//=> [1, 3]
arrayNonUniq(["foo", "foo", "bar", "foo"])
//=> ['foo']
You can also use the npm package array-non-uniq.
The following function (a variation of the eliminateDuplicates function already mentioned) seems to do the trick, returning test2,1,7,5 for the input ["test", "test2", "test2", 1, 1, 1, 2, 3, 4, 5, 6, 7, 7, 10, 22, 43, 1, 5, 8]
Note that the problem is stranger in JavaScript than in most other languages, because a JavaScript array can hold just about anything. Note that solutions that use sorting might need to provide an appropriate sorting function--I haven't tried that route yet.
This particular implementation works for (at least) strings and numbers.
function findDuplicates(arr) {
var i,
len=arr.length,
out=[],
obj={};
for (i=0;i<len;i++) {
if (obj[arr[i]] != null) {
if (!obj[arr[i]]) {
out.push(arr[i]);
obj[arr[i]] = 1;
}
} else {
obj[arr[i]] = 0;
}
}
return out;
}
var arr = [2, 1, 2, 2, 4, 4, 2, 5];
function returnDuplicates(arr) {
return arr.reduce(function(dupes, val, i) {
if (arr.indexOf(val) !== i && dupes.indexOf(val) === -1) {
dupes.push(val);
}
return dupes;
}, []);
}
alert(returnDuplicates(arr));
This function avoids the sorting step and uses the reduce() method to push duplicates to a new array if it doesn't already exist in it.
Related
Google Apps Script: How to merge two arrays conditionally?
I have a 2D array having a title in its first element of its 1D array and "trailing" or not at the beginning of the title. I like to add trailing data to the end of its same category parent data, "InterestExpense" or "IncomeTax". How can I do that? array = [['trailingInterestExpense', 4], ['InterestExpense', 1, 2, 3], ['trailingIncomeTax', 4], ['IncomeTax', 10, 20, 30]] My expected result is: array = [['InterestExpense', 1, 2, 3, 4],['IncomeTax', 10, 20, 30, 40]]
From your expected value of array = [['InterestExpense', 1, 2, 3, 4],['IncomeTax', 10, 20, 30, 40]], I guessed your ['trailingIncomeTax', 4] might be ['trailingIncomeTax', 40]. If my understanding is correct, how about the following sample script? Sample script: const keys = ["InterestExpense", "IncomeTax"]; // This is from your question. const array = [['trailingInterestExpense', 4], ['InterestExpense', 1, 2, 3], ['trailingIncomeTax', 40], ['IncomeTax', 10, 20, 30]]; // This is from your question. const obj = array.reduce((o, [a, ...b]) => { const key = keys.find(k => a.includes(k)); if (key) o[key] = o[key] ? [...o[key], ...b] : b; return o; }, {}); const res = keys.map(k => [k, ...obj[k].sort((a, b) => a - b)]); console.log(res) // [["InterestExpense",1,2,3,4],["IncomeTax",10,20,30,40]] References: reduce() map()
I made a small change to #Tanaike's, adding array.sort((a, b) => (a[0].charCodeAt(0) - b[0].charCodeAt(0))) right after "var array", because in a real world situation trailing data are placed randomly in the array, and depending on its index location, the output from #Tanaike's code was different. function test() { const keys = ["InterestExpense", "IncomeTax"]; // This is from your question. var array = [['trailingInterestExpense', 0.4], ['InterestExpense', 1, 2, 3], ['trailingIncomeTax', 0.4], ['IncomeTax', 10, 20, 30]]; // This is from your question. // Added this line to rearrange trailing data to the end of the array array.sort((a, b) => (a[0].charCodeAt(0) - b[0].charCodeAt(0))); console.log(array) const obj = array.reduce((o, [a, ...b]) => { const key = keys.find(k => a.includes(k)); if (key) o[key] = o[key] ? [...o[key], ...b] : b; return o; }, {}); const res = keys.map(k => [k, ...obj[k]]); console.log(res) // [["InterestExpense",1,2,3,0.4],["IncomeTax",10,20,30,0.4]] }
Why is my array only updating in view once?
i am doing a project to help visualize sorting algorithms and I'm facing a problem. To help visualize the sorting process of an algorithm, I must show every changings in the array during that said process. The problem is that my array is updating in my view only once the sort is done and not during the process. There are only integers in my arrays. Here is my code to display the array : <span *ngFor="let v of tab"> {{v}} </span And here is my controller : (the timeout is used to slow down the process) public sort(tab) { let start = performance.now(); console.log(start); let smallest; for (let i = 0; i < tab.length; i++) { smallest = tab[i]; for (let j = i + 1; j < tab.length; j++) { setTimeout(() => { }, 100000); if (tab[j] < smallest) { let tmp = tab[j]; tab[j] = smallest; tab[i] = tmp; smallest = tmp; //This doesn't update the view this.tab = tab; } } } //This does this.tab = tab; let end = performance.now(); console.log(end); this.time = end - start; The algo is probably not the most efficient but that's not the case ^^.
Its because setTimeout(() => { }, 100000); is not a synchronous operation. It will not wait for 100000ms for the next operation, it will just continue with synchronous operations and schedule timeout for some other time (You can read about Event Loop in javascript to understand that part) There are several ways to resolve this, you can do recursion (not really good), you can make an async function (you can read about async/await in javascript), and you can use reactive approach with RxJS (Angular is using it already), so something like: const sort = (tab: number []) => { let smallest: number; // First "loop" (iterate i (0, 1, 2, 3 ...)) range(0, tab.length) .pipe( // Set smallest tap(i => smallest = tab[i]), // Second loop (i + 1, i + 2, i + 3 ...) and map i and j to [i, j] mergeMap((i: number) => range(i + 1, tab.length - i - 1).pipe(map(j => [i, j]))), // Make delay concatMap(x => of(x).pipe(delay(1000))) ).subscribe(([i ,j]) => { if (tab[j] < smallest) { [tab[i], tab[j]] = [tab[j], tab[i]]; smallest = tab[j]; // Here if you can set // this.tab = tab; and you will see changes } }) }
Q. Check if 2 arrays have the same values in the same order
I have looked at other posts that supposedly have solved this issue, but this method still doesn't work for me. I had run into an error in a larger program I was writing but I narrowed the error to this method. I set a cell to =isMatch( {1,2,3} , {1,2,3} ) to verify my method works. The cell computes to False, and I don't know why or how to fix it. Before I checked stackoverflow, I had originally written code identical to the answer of this post. Here is the code I currently have. function isMatch(arr1,arr2){//Returns True if same Array values in same location if(arr1.length !== arr2.length) return false; for(var i =0; i<arr1.length; i++) { if(arr1[i] !== arr2[i]) return false; } return true; }
You're comparing a 2D array. {1,2,3} === [[1,2,3]] and not [1,2,3]. To compare a n dimensional array, you can recurse: function isMatch(arr1, arr2) { if (typeof arr1 !== typeof arr2) throw new TypeError('Arrays or elements not of same type!'); if (Array.isArray(arr1)) return ( arr1.length === arr2.length && arr1.every((e, i) => isMatch(e, arr2[i])) ); return arr1 === arr2; } console.info(isMatch([[1], [2]], [[1], [2]])); console.info(isMatch([[1, 2]], [[1, 2]])); console.info(isMatch([[1, 2]], 1)); 2D array Array#every
How to completely drop a attribute from JSON? [duplicate]
How do I remove a specific value from an array? Something like: array.remove(value); Constraints: I have to use core JavaScript. Frameworks are not allowed.
Find the index of the array element you want to remove using indexOf, and then remove that index with splice. The splice() method changes the contents of an array by removing existing elements and/or adding new elements. const array = [2, 5, 9]; console.log(array); const index = array.indexOf(5); if (index > -1) { // only splice array when item is found array.splice(index, 1); // 2nd parameter means remove one item only } // array = [2, 9] console.log(array); The second parameter of splice is the number of elements to remove. Note that splice modifies the array in place and returns a new array containing the elements that have been removed. For the reason of completeness, here are functions. The first function removes only a single occurrence (i.e. removing the first match of 5 from [2,5,9,1,5,8,5]), while the second function removes all occurrences: function removeItemOnce(arr, value) { var index = arr.indexOf(value); if (index > -1) { arr.splice(index, 1); } return arr; } function removeItemAll(arr, value) { var i = 0; while (i < arr.length) { if (arr[i] === value) { arr.splice(i, 1); } else { ++i; } } return arr; } // Usage console.log(removeItemOnce([2,5,9,1,5,8,5], 5)) console.log(removeItemAll([2,5,9,1,5,8,5], 5)) In TypeScript, these functions can stay type-safe with a type parameter: function removeItem<T>(arr: Array<T>, value: T): Array<T> { const index = arr.indexOf(value); if (index > -1) { arr.splice(index, 1); } return arr; }
Edited on 2016 October Do it simple, intuitive and explicit (Occam's razor) Do it immutable (original array stays unchanged) Do it with standard JavaScript functions, if your browser doesn't support them - use polyfill In this code example I use array.filter(...) function to remove unwanted items from an array. This function doesn't change the original array and creates a new one. If your browser doesn't support this function (e.g. Internet Explorer before version 9, or Firefox before version 1.5), consider polyfilling with core-js. Removing item (ECMA-262 Edition 5 code AKA old style JavaScript) var value = 3 var arr = [1, 2, 3, 4, 5, 3] arr = arr.filter(function(item) { return item !== value }) console.log(arr) // [ 1, 2, 4, 5 ] Removing item (ECMAScript 6 code) let value = 3 let arr = [1, 2, 3, 4, 5, 3] arr = arr.filter(item => item !== value) console.log(arr) // [ 1, 2, 4, 5 ] IMPORTANT ECMAScript 6 () => {} arrow function syntax is not supported in Internet Explorer at all, Chrome before version 45, Firefox before version 22, and Safari before version 10. To use ECMAScript 6 syntax in old browsers you can use BabelJS. Removing multiple items (ECMAScript 7 code) An additional advantage of this method is that you can remove multiple items let forDeletion = [2, 3, 5] let arr = [1, 2, 3, 4, 5, 3] arr = arr.filter(item => !forDeletion.includes(item)) // !!! Read below about array.includes(...) support !!! console.log(arr) // [ 1, 4 ] IMPORTANT array.includes(...) function is not supported in Internet Explorer at all, Chrome before version 47, Firefox before version 43, Safari before version 9, and Edge before version 14 but you can polyfill with core-js. Removing multiple items (in the future, maybe) If the "This-Binding Syntax" proposal is ever accepted, you'll be able to do this: // array-lib.js export function remove(...forDeletion) { return this.filter(item => !forDeletion.includes(item)) } // main.js import { remove } from './array-lib.js' let arr = [1, 2, 3, 4, 5, 3] // :: This-Binding Syntax Proposal // using "remove" function as "virtual method" // without extending Array.prototype arr = arr::remove(2, 3, 5) console.log(arr) // [ 1, 4 ] Try it yourself in BabelJS :) Reference Array.prototype.includes Functional composition
I don't know how you are expecting array.remove(int) to behave. There are three possibilities I can think of that you might want. To remove an element of an array at an index i: array.splice(i, 1); If you want to remove every element with value number from the array: for (var i = array.length - 1; i >= 0; i--) { if (array[i] === number) { array.splice(i, 1); } } If you just want to make the element at index i no longer exist, but you don't want the indexes of the other elements to change: delete array[i];
It depends on whether you want to keep an empty spot or not. If you do want an empty slot: array[index] = undefined; If you don't want an empty slot: //To keep the original: //oldArray = [...array]; //This modifies the array. array.splice(index, 1); And if you need the value of that item, you can just store the returned array's element: var value = array.splice(index, 1)[0]; If you want to remove at either end of the array, you can use array.pop() for the last one or array.shift() for the first one (both return the value of the item as well). If you don't know the index of the item, you can use array.indexOf(item) to get it (in a if() to get one item or in a while() to get all of them). array.indexOf(item) returns either the index or -1 if not found.
A friend was having issues in Internet Explorer 8 and showed me what he did. I told him it was wrong, and he told me he got the answer here. The current top answer will not work in all browsers (Internet Explorer 8 for example), and it will only remove the first occurrence of the item. Remove ALL instances from an array function removeAllInstances(arr, item) { for (var i = arr.length; i--;) { if (arr[i] === item) arr.splice(i, 1); } } It loops through the array backwards (since indices and length will change as items are removed) and removes the item if it's found. It works in all browsers.
There are two major approaches splice(): anArray.splice(index, 1); let fruits = ['Apple', 'Banana', 'Mango', 'Orange'] let removed = fruits.splice(2, 1); // fruits is ['Apple', 'Banana', 'Orange'] // removed is ['Mango'] delete: delete anArray[index]; let fruits = ['Apple', 'Banana', 'Mango', 'Orange'] let removed = delete fruits(2); // fruits is ['Apple', 'Banana', undefined, 'Orange'] // removed is true Be careful when you use the delete for an array. It is good for deleting attributes of objects, but not so good for arrays. It is better to use splice for arrays. Keep in mind that when you use delete for an array you could get wrong results for anArray.length. In other words, delete would remove the element, but it wouldn't update the value of the length property. You can also expect to have holes in index numbers after using delete, e.g. you could end up with having indexes 1, 3, 4, 8, 9, and 11 and length as it was before using delete. In that case, all indexed for loops would crash, since indexes are no longer sequential. If you are forced to use delete for some reason, then you should use for each loops when you need to loop through arrays. As the matter of fact, always avoid using indexed for loops, if possible. That way the code would be more robust and less prone to problems with indexes.
Array.prototype.removeByValue = function (val) { for (var i = 0; i < this.length; i++) { if (this[i] === val) { this.splice(i, 1); i--; } } return this; } var fruits = ['apple', 'banana', 'carrot', 'orange']; fruits.removeByValue('banana'); console.log(fruits); // -> ['apple', 'carrot', 'orange']
There isn't any need to use indexOf or splice. However, it performs better if you only want to remove one occurrence of an element. Find and move (move): function move(arr, val) { var j = 0; for (var i = 0, l = arr.length; i < l; i++) { if (arr[i] !== val) { arr[j++] = arr[i]; } } arr.length = j; } Use indexOf and splice (indexof): function indexof(arr, val) { var i; while ((i = arr.indexOf(val)) != -1) { arr.splice(i, 1); } } Use only splice (splice): function splice(arr, val) { for (var i = arr.length; i--;) { if (arr[i] === val) { arr.splice(i, 1); } } } Run-times on Node.js for an array with 1000 elements (averaged over 10,000 runs): indexof is approximately 10 times slower than move. Even if improved by removing the call to indexOf in splice, it performs much worse than move. Remove all occurrences: move 0.0048 ms indexof 0.0463 ms splice 0.0359 ms Remove first occurrence: move_one 0.0041 ms indexof_one 0.0021 ms
This provides a predicate instead of a value. NOTE: it will update the given array, and return the affected rows. Usage var removed = helper.remove(arr, row => row.id === 5 ); var removed = helper.removeAll(arr, row => row.name.startsWith('BMW')); Definition var helper = { // Remove and return the first occurrence remove: function(array, predicate) { for (var i = 0; i < array.length; i++) { if (predicate(array[i])) { return array.splice(i, 1); } } }, // Remove and return all occurrences removeAll: function(array, predicate) { var removed = []; for (var i = 0; i < array.length; ) { if (predicate(array[i])) { removed.push(array.splice(i, 1)); continue; } i++; } return removed; }, };
You can do it easily with the filter method: function remove(arrOriginal, elementToRemove){ return arrOriginal.filter(function(el){return el !== elementToRemove}); } console.log(remove([1, 2, 1, 0, 3, 1, 4], 1)); This removes all elements from the array and also works faster than a combination of slice and indexOf.
Using filter is an elegant way to achieve this requirement. filter will not mutate the original array. const num = 3; let arr = [1, 2, 3, 4]; const arr2 = arr.filter(x => x !== num); console.log(arr); // [1, 2, 3, 4] console.log(arr2); // [1, 2, 4] You can use filter and then assign the result to the original array if you want to achieve a mutation removal behaviour. const num = 3; let arr = [1, 2, 3, 4]; arr = arr.filter(x => x !== num); console.log(arr); // [1, 2, 4] By the way, filter will remove all of the occurrences matched in the condition (not just the first occurrence) like you can see in the following example const num = 3; let arr = [1, 2, 3, 3, 3, 4]; arr = arr.filter(x => x !== num); console.log(arr); // [1, 2, 4] In case, you just want to remove the first occurrence, you can use the splice method const num = 3; let arr = [1, 2, 3, 3, 3, 4]; const idx = arr.indexOf(num); arr.splice(idx, idx !== -1 ? 1 : 0); console.log(arr); // [1, 2, 3, 3, 4]
John Resig posted a good implementation: // Array Remove - By John Resig (MIT Licensed) Array.prototype.remove = function(from, to) { var rest = this.slice((to || from) + 1 || this.length); this.length = from < 0 ? this.length + from : from; return this.push.apply(this, rest); }; If you don’t want to extend a global object, you can do something like the following, instead: // Array Remove - By John Resig (MIT Licensed) Array.remove = function(array, from, to) { var rest = array.slice((to || from) + 1 || array.length); array.length = from < 0 ? array.length + from : from; return array.push.apply(array, rest); }; But the main reason I am posting this is to warn users against the alternative implementation suggested in the comments on that page (Dec 14, 2007): Array.prototype.remove = function(from, to) { this.splice(from, (to=[0, from || 1, ++to - from][arguments.length]) < 0 ? this.length + to : to); return this.length; }; It seems to work well at first, but through a painful process I discovered it fails when trying to remove the second to last element in an array. For example, if you have a 10-element array and you try to remove the 9th element with this: myArray.remove(8); You end up with an 8-element array. I don't know why, but I confirmed John's original implementation doesn't have this problem.
You can use ES6. For example to delete the value '3' in this case: var array=['1','2','3','4','5','6'] var newArray = array.filter((value)=>value!='3'); console.log(newArray); Output : ["1", "2", "4", "5", "6"]
Underscore.js can be used to solve issues with multiple browsers. It uses in-build browser methods if present. If they are absent like in the case of older Internet Explorer versions it uses its own custom methods. A simple example to remove elements from array (from the website): _.without([1, 2, 1, 0, 3, 1, 4], 0, 1); // => [2, 3, 4]
If you want a new array with the deleted positions removed, you can always delete the specific element and filter out the array. It might need an extension of the array object for browsers that don't implement the filter method, but in the long term it's easier since all you do is this: var my_array = [1, 2, 3, 4, 5, 6]; delete my_array[4]; console.log(my_array.filter(function(a){return typeof a !== 'undefined';})); It should display [1, 2, 3, 4, 6].
Here are a few ways to remove an item from an array using JavaScript. All the method described do not mutate the original array, and instead create a new one. If you know the index of an item Suppose you have an array, and you want to remove an item in position i. One method is to use slice(): const items = ['a', 'b', 'c', 'd', 'e', 'f'] const i = 3 const filteredItems = items.slice(0, i).concat(items.slice(i+1, items.length)) console.log(filteredItems) slice() creates a new array with the indexes it receives. We simply create a new array, from start to the index we want to remove, and concatenate another array from the first position following the one we removed to the end of the array. If you know the value In this case, one good option is to use filter(), which offers a more declarative approach: const items = ['a', 'b', 'c', 'd', 'e', 'f'] const valueToRemove = 'c' const filteredItems = items.filter(item => item !== valueToRemove) console.log(filteredItems) This uses the ES6 arrow functions. You can use the traditional functions to support older browsers: const items = ['a', 'b', 'c', 'd', 'e', 'f'] const valueToRemove = 'c' const filteredItems = items.filter(function(item) { return item !== valueToRemove }) console.log(filteredItems) or you can use Babel and transpile the ES6 code back to ES5 to make it more digestible to old browsers, yet write modern JavaScript in your code. Removing multiple items What if instead of a single item, you want to remove many items? Let's find the simplest solution. By index You can just create a function and remove items in series: const items = ['a', 'b', 'c', 'd', 'e', 'f'] const removeItem = (items, i) => items.slice(0, i-1).concat(items.slice(i, items.length)) let filteredItems = removeItem(items, 3) filteredItems = removeItem(filteredItems, 5) //["a", "b", "c", "d"] console.log(filteredItems) By value You can search for inclusion inside the callback function: const items = ['a', 'b', 'c', 'd', 'e', 'f'] const valuesToRemove = ['c', 'd'] const filteredItems = items.filter(item => !valuesToRemove.includes(item)) // ["a", "b", "e", "f"] console.log(filteredItems) Avoid mutating the original array splice() (not to be confused with slice()) mutates the original array, and should be avoided. (originally posted on my site https://flaviocopes.com/how-to-remove-item-from-array/)
Check out this code. It works in every major browser. remove_item = function(arr, value) { var b = ''; for (b in arr) { if (arr[b] === value) { arr.splice(b, 1); break; } } return arr; }; var array = [1,3,5,6,5,9,5,3,55] var res = remove_item(array,5); console.log(res)
Removing a particular element/string from an array can be done in a one-liner: theArray.splice(theArray.indexOf("stringToRemoveFromArray"), 1); where: theArray: the array you want to remove something particular from stringToRemoveFromArray: the string you want to be removed and 1 is the number of elements you want to remove. NOTE: If "stringToRemoveFromArray" is not located in the array, this will remove the last element of the array. It's always good practice to check if the element exists in your array first, before removing it. if (theArray.indexOf("stringToRemoveFromArray") >= 0){ theArray.splice(theArray.indexOf("stringToRemoveFromArray"), 1); } Depending if you have newer or older version of Ecmascript running on your client's computers: var array=['1','2','3','4','5','6'] var newArray = array.filter((value)=>value!='3'); OR var array = ['1','2','3','4','5','6']; var newArray = array.filter(function(item){ return item !== '3' }); Where '3' is the value you want to be removed from the array. The array would then become : ['1','2','4','5','6']
ES10 This post summarizes common approaches to element removal from an array as of ECMAScript 2019 (ES10). 1. General cases 1.1. Removing Array element by value using .splice() | In-place: Yes | | Removes duplicates: Yes(loop), No(indexOf) | | By value / index: By index | If you know the value you want to remove from an array you can use the splice method. First, you must identify the index of the target item. You then use the index as the start element and remove just one element. // With a 'for' loop const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]; for( let i = 0; i < arr.length; i++){ if ( arr[i] === 5) { arr.splice(i, 1); } } // => [1, 2, 3, 4, 6, 7, 8, 9, 0] // With the .indexOf() method const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]; const i = arr.indexOf(5); arr.splice(i, 1); // => [1, 2, 3, 4, 6, 7, 8, 9, 0] 1.2. Removing Array element using the .filter() method | In-place: No | | Removes duplicates: Yes | | By value / index: By value | The specific element can be filtered out from the array, by providing a filtering function. Such function is then called for every element in the array. const value = 3 let arr = [1, 2, 3, 4, 5, 3] arr = arr.filter(item => item !== value) console.log(arr) // [ 1, 2, 4, 5 ] 1.3. Removing Array element by extending Array.prototype | In-place: Yes/No (Depends on implementation) | | Removes duplicates: Yes/No (Depends on implementation) | | By value / index: By index / By value (Depends on implementation) | The prototype of Array can be extended with additional methods. Such methods will be then available to use on created arrays. Note: Extending prototypes of objects from the standard library of JavaScript (like Array) is considered by some as an antipattern. // In-place, removes all, by value implementation Array.prototype.remove = function(item) { for (let i = 0; i < this.length; i++) { if (this[i] === item) { this.splice(i, 1); } } } const arr1 = [1,2,3,1]; arr1.remove(1) // arr1 equals [2,3] // Non-stationary, removes first, by value implementation Array.prototype.remove = function(item) { const arr = this.slice(); for (let i = 0; i < this.length; i++) { if (arr[i] === item) { arr.splice(i, 1); return arr; } } return arr; } let arr2 = [1,2,3,1]; arr2 = arr2.remove(1) // arr2 equals [2,3,1] 1.4. Removing Array element using the delete operator | In-place: Yes | | Removes duplicates: No | | By value / index: By index | Using the delete operator does not affect the length property. Nor does it affect the indexes of subsequent elements. The array becomes sparse, which is a fancy way of saying the deleted item is not removed but becomes undefined. const arr = [1, 2, 3, 4, 5, 6]; delete arr[4]; // Delete element with index 4 console.log( arr ); // [1, 2, 3, 4, undefined, 6] The delete operator is designed to remove properties from JavaScript objects, which arrays are objects. 1.5. Removing Array element using Object utilities (>= ES10) | In-place: No | | Removes duplicates: Yes | | By value / index: By value | ES10 introduced Object.fromEntries, which can be used to create the desired Array from any Array-like object and filter unwanted elements during the process. const object = [1,2,3,4]; const valueToRemove = 3; const arr = Object.values(Object.fromEntries( Object.entries(object) .filter(([ key, val ]) => val !== valueToRemove) )); console.log(arr); // [1,2,4] 2. Special cases 2.1 Removing element if it's at the end of the Array 2.1.1. Changing Array length | In-place: Yes | | Removes duplicates: No | | By value / index: N/A | JavaScript Array elements can be removed from the end of an array by setting the length property to a value less than the current value. Any element whose index is greater than or equal to the new length will be removed. const arr = [1, 2, 3, 4, 5, 6]; arr.length = 5; // Set length to remove element console.log( arr ); // [1, 2, 3, 4, 5] 2.1.2. Using .pop() method | In-place: Yes | | Removes duplicates: No | | By value / index: N/A | The pop method removes the last element of the array, returns that element, and updates the length property. The pop method modifies the array on which it is invoked, This means unlike using delete the last element is removed completely and the array length reduced. const arr = [1, 2, 3, 4, 5, 6]; arr.pop(); // returns 6 console.log( arr ); // [1, 2, 3, 4, 5] 2.2. Removing element if it's at the beginning of the Array | In-place: Yes | | Removes duplicates: No | | By value / index: N/A | The .shift() method works much like the pop method except it removes the first element of a JavaScript array instead of the last. When the element is removed the remaining elements are shifted down. const arr = [1, 2, 3, 4]; arr.shift(); // returns 1 console.log( arr ); // [2, 3, 4] 2.3. Removing element if it's the only element in the Array | In-place: Yes | | Removes duplicates: N/A | | By value / index: N/A | The fastest technique is to set an array variable to an empty array. let arr = [1]; arr = []; //empty array Alternatively technique from 2.1.1 can be used by setting length to 0.
You can use lodash _.pull (mutate array), _.pullAt (mutate array) or _.without (does't mutate array), var array1 = ['a', 'b', 'c', 'd'] _.pull(array1, 'c') console.log(array1) // ['a', 'b', 'd'] var array2 = ['e', 'f', 'g', 'h'] _.pullAt(array2, 0) console.log(array2) // ['f', 'g', 'h'] var array3 = ['i', 'j', 'k', 'l'] var newArray = _.without(array3, 'i') // ['j', 'k', 'l'] console.log(array3) // ['i', 'j', 'k', 'l']
ES6 & without mutation: (October 2016) const removeByIndex = (list, index) => [ ...list.slice(0, index), ...list.slice(index + 1) ]; output = removeByIndex([33,22,11,44],1) //=> [33,11,44] console.log(output)
Performance Today (2019-12-09) I conduct performance tests on macOS v10.13.6 (High Sierra) for chosen solutions. I show delete (A), but I do not use it in comparison with other methods, because it left empty space in the array. The conclusions the fastest solution is array.splice (C) (except Safari for small arrays where it has the second time) for big arrays, array.slice+splice (H) is the fastest immutable solution for Firefox and Safari; Array.from (B) is fastest in Chrome mutable solutions are usually 1.5x-6x faster than immutable for small tables on Safari, surprisingly the mutable solution (C) is slower than the immutable solution (G) Details In tests, I remove the middle element from the array in different ways. The A, C solutions are in-place. The B, D, E, F, G, H solutions are immutable. Results for an array with 10 elements In Chrome the array.splice (C) is the fastest in-place solution. The array.filter (D) is the fastest immutable solution. The slowest is array.slice (F). You can perform the test on your machine here. Results for an array with 1.000.000 elements In Chrome the array.splice (C) is the fastest in-place solution (the delete (C) is similar fast - but it left an empty slot in the array (so it does not perform a 'full remove')). The array.slice-splice (H) is the fastest immutable solution. The slowest is array.filter (D and E). You can perform the test on your machine here. var a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]; var log = (letter,array) => console.log(letter, array.join `,`); function A(array) { var index = array.indexOf(5); delete array[index]; log('A', array); } function B(array) { var index = array.indexOf(5); var arr = Array.from(array); arr.splice(index, 1) log('B', arr); } function C(array) { var index = array.indexOf(5); array.splice(index, 1); log('C', array); } function D(array) { var arr = array.filter(item => item !== 5) log('D', arr); } function E(array) { var index = array.indexOf(5); var arr = array.filter((item, i) => i !== index) log('E', arr); } function F(array) { var index = array.indexOf(5); var arr = array.slice(0, index).concat(array.slice(index + 1)) log('F', arr); } function G(array) { var index = array.indexOf(5); var arr = [...array.slice(0, index), ...array.slice(index + 1)] log('G', arr); } function H(array) { var index = array.indexOf(5); var arr = array.slice(0); arr.splice(index, 1); log('H', arr); } A([...a]); B([...a]); C([...a]); D([...a]); E([...a]); F([...a]); G([...a]); H([...a]); This snippet only presents code used in performance tests - it does not perform tests itself. Comparison for browsers: Chrome v78.0.0, Safari v13.0.4, and Firefox v71.0.0
OK, for example you have the array below: var num = [1, 2, 3, 4, 5]; And we want to delete number 4. You can simply use the below code: num.splice(num.indexOf(4), 1); // num will be [1, 2, 3, 5]; If you are reusing this function, you write a reusable function which will be attached to the native array function like below: Array.prototype.remove = Array.prototype.remove || function(x) { const i = this.indexOf(x); if(i===-1) return; this.splice(i, 1); // num.remove(5) === [1, 2, 3]; } But how about if you have the below array instead with a few [5]s in the array? var num = [5, 6, 5, 4, 5, 1, 5]; We need a loop to check them all, but an easier and more efficient way is using built-in JavaScript functions, so we write a function which use a filter like below instead: const _removeValue = (arr, x) => arr.filter(n => n!==x); //_removeValue([1, 2, 3, 4, 5, 5, 6, 5], 5) // Return [1, 2, 3, 4, 6] Also there are third-party libraries which do help you to do this, like Lodash or Underscore. For more information, look at lodash _.pull, _.pullAt or _.without.
I'm pretty new to JavaScript and needed this functionality. I merely wrote this: function removeFromArray(array, item, index) { while((index = array.indexOf(item)) > -1) { array.splice(index, 1); } } Then when I want to use it: //Set-up some dummy data var dummyObj = {name:"meow"}; var dummyArray = [dummyObj, "item1", "item1", "item2"]; //Remove the dummy data removeFromArray(dummyArray, dummyObj); removeFromArray(dummyArray, "item2"); Output - As expected. ["item1", "item1"] You may have different needs than I, so you can easily modify it to suit them. I hope this helps someone.
I want to answer based on ECMAScript 6. Assume you have an array like below: let arr = [1,2,3,4]; If you want to delete at a special index like 2, write the below code: arr.splice(2, 1); //=> arr became [1,2,4] But if you want to delete a special item like 3 and you don't know its index, do like below: arr = arr.filter(e => e !== 3); //=> arr became [1,2,4] Hint: please use an arrow function for filter callback unless you will get an empty array.
If you have complex objects in the array you can use filters? In situations where $.inArray or array.splice is not as easy to use. Especially if the objects are perhaps shallow in the array. E.g. if you have an object with an Id field and you want the object removed from an array: this.array = this.array.filter(function(element, i) { return element.id !== idToRemove; });
Update: This method is recommended only if you cannot use ECMAScript 2015 (formerly known as ES6). If you can use it, other answers here provide much neater implementations. This gist here will solve your problem, and also deletes all occurrences of the argument instead of just 1 (or a specified value). Array.prototype.destroy = function(obj){ // Return null if no objects were found and removed var destroyed = null; for(var i = 0; i < this.length; i++){ // Use while-loop to find adjacent equal objects while(this[i] === obj){ // Remove this[i] and store it within destroyed destroyed = this.splice(i, 1)[0]; } } return destroyed; } Usage: var x = [1, 2, 3, 3, true, false, undefined, false]; x.destroy(3); // => 3 x.destroy(false); // => false x; // => [1, 2, true, undefined] x.destroy(true); // => true x.destroy(undefined); // => undefined x; // => [1, 2] x.destroy(3); // => null x; // => [1, 2]
You should never mutate your array as this is against the functional programming pattern. You can create a new array without referencing the one you want to change data of using the ECMAScript 6 method filter; var myArray = [1, 2, 3, 4, 5, 6]; Suppose you want to remove 5 from the array, you can simply do it like this: myArray = myArray.filter(value => value !== 5); This will give you a new array without the value you wanted to remove. So the result will be: [1, 2, 3, 4, 6]; // 5 has been removed from this array For further understanding you can read the MDN documentation on Array.filter.
A more modern, ECMAScript 2015 (formerly known as Harmony or ES 6) approach. Given: const items = [1, 2, 3, 4]; const index = 2; Then: items.filter((x, i) => i !== index); Yielding: [1, 2, 4] You can use Babel and a polyfill service to ensure this is well supported across browsers.
You can do a backward loop to make sure not to screw up the indexes, if there are multiple instances of the element. var myElement = "chocolate"; var myArray = ['chocolate', 'poptart', 'poptart', 'poptart', 'chocolate', 'poptart', 'poptart', 'chocolate']; /* Important code */ for (var i = myArray.length - 1; i >= 0; i--) { if (myArray[i] == myElement) myArray.splice(i, 1); } console.log(myArray);
merge json object with arrays
Suppose I have two json objects and I need to merge them. css: [{ drag: "mode() == 'layout'", ui_draggable: "mode() == 'layout'" }] css: [{ someclass : true }] I want to end up with: css: [{ drag: "mode() == 'layout'", ui_draggable: "mode() == 'layout'", someclass : true }] After some further trial I came up with this but I assume I have place a few bugs or useless lines of code in it. I came up with this code after a little playing around. My needs didn't need to recurse more than two levels so this is just fine. It could be much refined I am sure but it works great for binding knockout. Here is an example of how I used it to extend jquery unobtrusive knockoutjs var settings = { text: 'SelectedCard().CardData.Title', visible: "mode() != 'edit' || !isMyCard()", css: [{ drag: "mode() == 'layout'" , selectedElement: "selectedCardElement() == '_titlePreview'"}] }; var settings2 = { css: [{ drag: "mode() == 'layout'"}] }; var settings3 = merge(settings, settings2); function merge(first, second) { for (var a1 in first) { // if second object is null we are finished. used.push(a1); if (second[a1] == null) { continue; } else { var ob2 = second[a1]; if (typeof (first[a1]) != typeof (ob2)) { throw new Error("conflicting properties named:" + a1); } if ($.isArray(first[a1])) { for (var i = 0; i < ob2.length; i++) { first[a1].push(ob2[i]); } } else { // matching property. return merge(first[a1], second[a1]); } } } for (var a2 in second) { if (used.indexOf(a2) < 0) { first[a2] = second[a2]; } } return first; }
1) To merge both objects with a one-way overwrite, this will do it: for (var attrname in obj2) { obj1[attrname] = obj2[attrname]; } 2) To merge selectively, both ways: obj1.someclass = obj2.someclass; -or- obj2["someclass"] = obj1["someclass"]; In this case, if the property does not yet exist in the object it does not need to be defined before assigning it. 3) Consider using a library like Underscore.js for performing "array functions" similar to this: _.union([1, 2, 3], [101, 2, 1, 10], [2, 1]); returns [1, 2, 3, 101, 10] 4) Lastly, here's a strong resource for formatting JSON objects, arrays and a combination thereof: jsonexample.com. This will be helpful as you get into complex "array functions". Cheers!