Remove first element from a multi-dimension array in javascript - javascript

I have an array like :
var arr = [["series0","44","24",56,12 ]]
How to trim(remove) the first element, here it is "series0" ?
I already tried most predefined js function but could not find solution.
Thanks all for great answers.What would be best way to sort the array, i already tried for:
.sort(function(a, b){return a-b})
and also:
arr.sort(function(a,b) {
if (isNaN(a) || isNaN(b)) {
return a > b ? 1 : -1;
}
return a - b;
});
I need the sort result should return like arr=[["series0","12","24","44","56"]]
Rather i am getting [["12","24","44","56","series0"]]

The shift method removes the first element, you can call it on the first element of your array:
arr[0].shift()

Use splice(), by changing second parameter you can remove more than one elements
var arr = [
["series0", "44", "54", 56]
];
arr[0].splice(0, 1);
document.write(JSON.stringify(arr));
EDIT : In case if you just want to remove single element then shift() will be best solution
var arr = [
["series0", "44", "54", 56]
];
arr[0].shift();
document.write(JSON.stringify(arr));

Try the .map function of Array:
var arr = [["series0", "44", "54",56 ]]
arr.map(function(arr){arr.shift()});
console.log(arr)
It'll remove all the first element of all elements of outer array.
input:
[["series0", "44", "54",56 ],["series0", "44", "54",56 ]]
output:
[["44", "54",56 ],["44", "54",56 ]]

Simply use the shift function:
Removes the first element from an array and returns only that element.
arr[0].shift();
alert(arr);

Use the array shift() method:
var arr = [["series0", "44", "54",56 ]]
arr[0].shift(); // removes and returns "series0" (return ignored here)

Related

Use index array to filter another array

I have two arrays
arr = [ aaa, xxx, aaa, xxx, aaa ];
foundIn = [ 1, 3 ];
As you can see foundIn has the index numbers of arr that I would like to remove. How can I remove the values in arr using the the index values in foundIn
The output being: newArr = [ aaa, aaa, aaa ];
This is a simplified version of my issue.
Any help in this would be greatly appreciated.
You can utilize the native javascript .filter() method to solve this kind of problem.
var arr = ["aaa", "xxx", "aaa", "xxx", "aaa"];
var foundIn = [1, 3];
var res = arr.filter(function (eachElem, index) {
return foundIn.indexOf(index) == -1
})
console.log(res) // ["aaa", "aaa", "aaa"]
Explanation
The callback will be executed in each loop on where this function is called (in the example above example, it will be used on arr variable).
Two arguments are passed into the callback. First is the element, and the second is the index. Because you need the index, you have to write all those two arguments, even though you are not using the first argument.
In this issue, the index variable is used to determine whether it exists on the foundIn variable or not (we use .indexOf() method to do the checking). If it's not exists, true will be given. So all returned element is the one which is not exists in the foundIn.
.indexOf() returns the index of the searched item, if it's not found, -1 is returned.
If you are using es6, you can simplify the code:
var res = arr.filter((d, i) => foundIn.indexOf(i) == -1)
Also try this working example:
var arr = ["aaa", "xxx", "aaa", "xxx", "aaa"];
var foundIn = [1, 3];
var res = arr.filter(function (eachElem, index) {
return foundIn.indexOf(index) == -1
})
document.write(JSON.stringify(res))
// ["aaa", "aaa", "aaa"]
You have several options.
Loop through foundIn in reverse index order (e.g., highest first; you could use sort to sort it) and use splice to remove those from the other array.
Use filter on arr and return false for indexes you don't find in foundIn (but it involves re-searching foundIn each time)
Build an object with index keys (or a Set of the indexes in ES2015 and above) from foundIn with keys for the indexes, and then use arr.filter looking up the indexes in the map to see if they should be removed.
The first two are trivial, I'll leave the coding to you. The last one may benefit from code for explanation:
var arr = ["aaa", "xxx", "aaa", "xxx", "aaa"];
var foundIn = [1, 3];
var map = Object.create(null);
foundIn.forEach(function(entry) {
map[entry] = true;
});
arr = arr.filter(function(_, index) {
return !map[index];
});
console.log(arr);
or in ES2015 (aka "ES6") and above:
let arr = ["aaa", "xxx", "aaa", "xxx", "aaa"];
let foundIn = [1, 3];
let set = new Set(foundIn);
arr = arr.filter((_, index) => !set.has(index));
console.log(arr);
I think i may have come up with something:
arr.flatMap( (x,i) => foundIn.includes( i ) ? [] : x )
Hope you like it.
you can use filter(el, index) to get that done:
arr.filter(function(el, index) {
return foundIn.indexOf(index) > -1;
});
filter returns an array with all the element's which the condition returned true for them.
In my exmaple, all elements which their index exists in foundIn

Is there any built in method to sort part of an array?

We can just simply use array.sort() (the array contains alphabets), but that will sort the whole array. But I just want to sort a part of the array like this:
Lets assume array = ["c" , "d" , "b" , "f" , "a" , "e"]. Now, instead of sorting it completely, I want to sort it from index 2 to 5 , so array becomes ["c" , "d" , "a" , "b" , "e" , "f"].
Is there any method in Array.prototype to do this?
NOTE: I can write a custom function to solve this problem, but I am avoiding it. Maybe I could just get a quick solution...
There is no function available that does exactly what you asked.
To achieve what you want, you'll have to do something like the following:
var array = ["c", "d", "b", "f", "a", "e"];
var array1 = array.splice(2, 4);
array1.sort();
array = array.concat(array1);
console.log(array);
Try this
var arr = ["c" , "d" , "b" , "f" , "a" , "e"];
var tmpArr = arr.slice(2,5);
tmpArr.sort();
arr = arr.slice(0,2).concat(tmpArr).concat(arr.slice(5));
document.body.innerHTML += JSON.stringify(arr,0,4);
The full list of Array prototype methods is here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/prototype.
The nearest thing I could find to what you want would be to use Array.slice to get 3 arrays: the elements before those you want to sort, the elements you want to sort and the elements after those you want to sort. Then use Array.sort to sort the desired elements. Finally glue the arrays back together with Array.concat.
.slice() will be good choice:
var arr = ["c" , "d" , "b" , "f" , "a" , "e"];
var o = arr.slice(0, 2); // take the first two out
var a = arr.slice(-4).sort(); // now slice back and sort it
var n = o.concat(a); // concat the two arrarys and return it.
document.querySelector('pre').innerHTML = JSON.stringify(n, 0, 0);
<pre></pre>

Remove a value from an array in CoffeeScript

I have an array:
array = [..., "Hello", "World", "Again", ...]
How could I check if "World" is in the array?
Then remove it if it exists?
And have a reference to "World"?
Sometimes maybe I wanna match a word with a regexp and in that case I won't know the exact string so I need to have a reference to the matched String. But in this case I know for sure it's "World" which makes it simpler.
Thanks for the suggestions. I found a cool way to do it:
http://documentcloud.github.com/underscore
filter() is also an option:
arr = [..., "Hello", "World", "Again", ...]
newArr = arr.filter (word) -> word isnt "World"
array.indexOf("World") will get the index of "World" or -1 if it doesn't exist. array.splice(indexOfWorld, 1) will remove "World" from the array.
For this is such a natural need, I often prototype my arrays with an remove(args...) method.
My suggestion is to write this somewhere:
Array.prototype.remove = (args...) ->
output = []
for arg in args
index = #indexOf arg
output.push #splice(index, 1) if index isnt -1
output = output[0] if args.length is 1
output
And use like this anywhere:
array = [..., "Hello", "World", "Again", ...]
ref = array.remove("World")
alert array # [..., "Hello", "Again", ...]
alert ref # "World"
This way you can also remove multiple items at the same time:
array = [..., "Hello", "World", "Again", ...]
ref = array.remove("Hello", "Again")
alert array # [..., "World", ...]
alert ref # ["Hello", "Again"]
Checking if "World" is in array:
"World" in array
Removing if exists
array = (x for x in array when x != 'World')
or
array = array.filter (e) -> e != 'World'
Keeping reference (that's the shortest I've found - !.push is always false since .push > 0)
refs = []
array = array.filter (e) -> e != 'World' || !refs.push e
Try this :
filter = ["a", "b", "c", "d", "e", "f", "g"]
#Remove "b" and "d" from the array in one go
filter.splice(index, 1) for index, value of filter when value in ["b", "d"]
A combination of a few answers:
Array::remove = (obj) ->
#filter (el) -> el isnt obj
_.without() function from the underscorejs library is a good and clean option in case you want to get a new array :
_.without([1, 2, 1, 0, 3, 1, 4], 0, 1)
[2, 3, 4]
CoffeeScript + jQuery:
remove one, not all
arrayRemoveItemByValue = (arr,value) ->
r=$.inArray(value, arr)
unless r==-1
arr.splice(r,1)
# return
arr
console.log arrayRemoveItemByValue(['2','1','3'],'3')

What's an easy way of storing an array of numbers in Javascript that I can add/remove from?

In C# I would create a List then I could add and remove numbers very easily. Does identical functionality exist in Javascript, or do I have to write my own methods to search and remove items using a loop?
var NumberList = [];
NumberList.Add(17);
NumberList.Add(25);
NumberList.Remove(17);
etc.
I know I can use .push to add a number, so I guess it's really how to remove an individual number without using a loop that I'm looking for.
edit: of course, if there's no other way then I'll use a loop!:)
The Array objet has this kind of method :
var myArray = new Array();
myArray.push(12);
myArray.push(10);
myArray.pop();
All detail can be found here
To remove a specific value , some tricks are possible :
var id = myArray.indexOf(10); // Find the index
if(id!=-1) myArray.splice(id, 1);
You have to use splice and indexOf if you know that there is only one copy of the value that you want to remove and if there can be many copies then you have to use splice in a loop.
If you're using Underscore.js then you can use:
array = _.without(array, 17);
To remove array element by value :
Array.prototype.removeByValue = function(val) {
for(var i=0; i<this.length; i++) {
if(this[i] == val) {
this.splice(i, 1);
break;
}
}
}
var myarray = ["one", "two", "three", "four", "five"];
myarray.removeByValue("three");
console.log(myarray); // ["one", "two", "four", "five"];
or in your case an array of numbers:
var myarray = [1, 2, 3, 4, 5];
myarray.removeByValue(3);
console.log(myarray); // [1, 2, 4, 5];
to remove by index you'll have to use splice():
myarray.splice(2,1); //position at 2nd element and remove 1 element
console.log(myarray); // ["one", "two", "four", "five"];
var NumberList = {};
NumberList[17] = true;
NumberList[25] = true;
delete NumberList[17];
This uses the "associative array"-characteristic of JavaScript objects to let you store and retrieve values by index in an object.
I used true as the value, but you can use anything you like, as it is not important (at least as per your example). You could of course store more useful things there. Using true has the nice side-effect that you can do an existence-check like this:
if (NumberList[25]) // evaluates to "true"
if (NumberList[26]) // evaluates to "undefined" (equivalent to "false" here)
The same would work with actual array objects, by the way.
var NumberList = [];
NumberList[17] = true;
NumberList[25] = true;
delete NumberList[17];
but these would not be "sparse" - NumberList[25] = true creates an 26-element array with all preceding array elements set to undefined.
Using objects instead is sparse, no additional members are created.
If you want in-place removal, then indexOf and splice can be used together. To remove all occurrences of 17, use
var index;
while((index = NumberList.indexOf(17)) != -1) {
NumberList.splice(index, 1);
}
If you don't care about in-place removals, then the filter method can be used.
NumberList = NumberList.filter(function(number) {
return number != 17;
});
You could store the index of each added element (number). And then use splice to remove by index. John has a good array remove function to remove by index.
Something like:
var array = [];
var number = { val: 10, index: null };
// add to array
array.push(number.val);
number.index = array.length - 1;
// remove (using John's remove function)
array.remove(number.index);
// remove using splice
array.splice(number.index, 1);
I've solved it by using the JQuery function inArray(); combined with splice().
indexOf and inArray seem to be identical, however indexOf isn't supported in IE6 or 7 as it turns out, so I had to either write my own or use JQuery, and I use JQuery anyway.

How to remove element from an array in JavaScript?

var arr = [1,2,3,5,6];
Remove the first element
I want to remove the first element of the array so that it becomes:
var arr = [2,3,5,6];
Remove the second element
To extend this question, what if I want to remove the second element of the array so that it becomes:
var arr = [1,3,5,6];
shift() is ideal for your situation. shift() removes the first element from an array and returns that element. This method changes the length of the array.
array = [1, 2, 3, 4, 5];
array.shift(); // 1
array // [2, 3, 4, 5]
For a more flexible solution, use the splice() function. It allows you to remove any item in an Array based on Index Value:
var indexToRemove = 0;
var numberToRemove = 1;
arr.splice(indexToRemove, numberToRemove);
arr.slice(begin[,end])
is non destructive, splice and shift will modify your original array
The Array.prototype.shift method removes the first element from an array, and returns it. It modifies the original array.
var a = [1,2,3]
// [1,2,3]
a.shift()
// 1
a
//[2,3]
Maybe something like this:
arr=arr.slice(1);
Wrote a small article about inserting and deleting elements at arbitrary positions in Javascript Arrays.
Here's the small snippet to remove an element from any position. This extends the Array class in Javascript and adds the remove(index) method.
// Remove element at the given index
Array.prototype.remove = function(index) {
this.splice(index, 1);
}
So to remove the first item in your example, call arr.remove():
var arr = [1,2,3,5,6];
arr.remove(0);
To remove the second item,
arr.remove(1);
Here's a tiny article with insert and delete methods for Array class.
Essentially this is no different than the other answers using splice, but the name splice is non-intuitive, and if you have that call all across your application, it just makes the code harder to read.
Others answers are great, I just wanted to add an alternative solution with ES6 Array function : filter.
filter() creates a new array with elements that fall under a given criteria from an existing array.
So you can easily use it to remove items that not pass the criteria. Benefits of this function is that you can use it on complex array not just string and number.
Some examples :
Remove first element :
// Not very useful but it works
function removeFirst(element, index) {
return index > 0;
}
var arr = [1,2,3,5,6].filter(removeFirst); // [2,3,4,5,6]
Remove second element :
function removeSecond(element, index) {
return index != 1;
}
var arr = [1,2,3,5,6].filter(removeSecond); // [1,3,4,5,6]
Remove odd element :
function removeOdd(element, index) {
return !(element % 2);
}
var arr = [1,2,3,5,6].filter(removeOdd); [2,4,6]
Remove items not in stock
const inventory = [
{name: 'Apple', qty: 2},
{name: 'Banana', qty: 0},
{name: 'Orange', qty: 5}
];
const res = inventory.find( product => product.qty > 0);
There are multiple ways to remove an element from an Array. Let me point out most used options below. I'm writing this answer because I couldn't find a proper reason as to what to use from all of these options. The answer to the question is option 3 (Splice()).
1) SHIFT() - Remove First Element from Original Array and Return the First Element
See reference for Array.prototype.shift(). Use this only if you want to remove the first element, and only if you are okay with changing the original array.
const array1 = [1, 2, 3];
const firstElement = array1.shift();
console.log(array1);
// expected output: Array [2, 3]
console.log(firstElement);
// expected output: 1
2) SLICE() - Returns a Copy of the Array, Separated by a Begin Index and an End Index
See reference for Array.prototype.slice(). You cannot remove a specific element from this option. You can take only slice the existing array and get a continuous portion of the array. It's like cutting the array from the indexes you specify. The original array does not get affected.
const animals = ['ant', 'bison', 'camel', 'duck', 'elephant'];
console.log(animals.slice(2));
// expected output: Array ["camel", "duck", "elephant"]
console.log(animals.slice(2, 4));
// expected output: Array ["camel", "duck"]
console.log(animals.slice(1, 5));
// expected output: Array ["bison", "camel", "duck", "elephant"]
3) SPLICE() - Change Contents of Array by Removing or Replacing Elements at Specific Indexes.
See reference for Array.prototype.splice(). The splice() method changes the contents of an array by removing or replacing existing elements and/or adding new elements in place. Returns updated array. Original array gets updated.
const months = ['Jan', 'March', 'April', 'June'];
months.splice(1, 0, 'Feb');
// inserts at index 1
console.log(months);
// expected output: Array ["Jan", "Feb", "March", "April", "June"]
months.splice(4, 1, 'May');
// replaces 1 element at index 4
console.log(months);
// expected output: Array ["Jan", "Feb", "March", "April", "May"]
You can use the ES6 Destructuring Assignment feature with a rest operator. A comma indicates where you want to remove the element and the rest (...arr) operator to give you the remaining elements of the array.
const source = [1,2,3,5,6];
function removeFirst(list) {
var [, ...arr] = list;
return arr;
}
const arr = removeFirst(source);
console.log(arr); // [2, 3, 5, 6]
console.log(source); // [1, 2, 3, 5, 6]
Typescript solution that does not mutate original array
function removeElementAtIndex<T>(input: T[], index: number) {
return input.slice(0, index).concat(input.slice(index + 1));
}
You can also do this with reduce:
let arr = [1, 2, 3]
arr.reduce((xs, x, index) => {
if (index == 0) {
return xs
} else {
return xs.concat(x)
}
}, Array())
// Or if you like a oneliner
arr.reduce((xs, x, index) => index == 0 ? xs : xs.concat(x), Array())
Array.splice() has the interesting property that one cannot use it to remove the first element. So, we need to resort to
function removeAnElement( array, index ) {
index--;
if ( index === -1 ) {
return array.shift();
} else {
return array.splice( index, 1 );
}
}

Categories

Resources