Creating array of empty strings? - javascript

Is there an easy way to create an array of empty strings in javascript? Currently the only way I can think to do it is with a loop:
var empty = new Array(someLength);
for(var i=0;i<empty.length;i++){
empty[i] = '';
}
but I'm wondering if there is some way to do this in one line using either regular javascript or coffeescript.

Update: on newer browsers - use .fill: Array(1000).fill('') will create an array of 1000 empty strings.
Yes, there is a way:
var n = 1000;
Array(n).join(".").split("."); // now contains n empty strings.
I'd probably use the loop though, it conveys intent clearer.
function repeat(num,whatTo){
var arr = [];
for(var i=0;i<num;i++){
arr.push(whatTo);
}
return arr;
}
That way, it's perfectly clear what's being done and you can reuse it.

You can get an array defining the size and fill it with some tokens:
const arr = Array(size).fill("");

here's a simpler way using generic protos on Array and String:
"".split.call(Array(1001), ",")
EDIT: There's now even simpler ways, some of which are readable:
Array(1000).fill("");
" ".repeat(999).split(" ");

You can try to do it by this way:
let n = 1000;
var emptyStrings = [...Array(n)].map(() => '')

Using Array.from;
const n = 5;
const arr = Array.from({length: n}).map(el => "")
console.log(arr)

You could make a function out of it:
function stringArray(length) {
var arr = [];
for(var i = 0; i < length; ++i) { arr.push(''); }
return arr;
}

You could do something like this:
var someLength = 10;
var empty = Array.apply(0, Array(someLength)).map(function(){return '';});
// result: ["", "", "", "", "", "", "", "", "", ""]

Just for fun
var empty = Array.apply(null, new Array(someLength)).map(String.prototype.valueOf,"");

The easiest thing to do in CoffeeScript is to use a loop comprehension:
a = ('' for i in [0 ... someLength]) # Note: 3 dots
a = ('' for i in [1 .. someLength]) # Or 2 dots and start at 1
#...
Demo: http://jsfiddle.net/ambiguous/b9Vj9/

Although not widely available, once browsers start supporting EcmaScript 6 array comprehensions, you will be able to do something along the lines of:
var n = 1000;
var empty_strs = ['' for (x of new Array(n))]

Easy enough.
Array with a length of 10 items, filled with empty strings (""):
Array.from({length: 10}).map( _ => "" );
// Array(10) [ "", "", "", "", "", "", "", "", "", "" ]
Array with a length of 10 items, filled with numbers from 0 to 9:
Array.from({length: 10}).map( (_, index) => index );
// Array(10) [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 ]
Array with a length of 10 items, filled with numbers from 1 to 10:
Array.from({length: 10}).map( (_, index) => index + 1 );
// Array(10) [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ]
Array with a length of 10 items, filled with string containing "Chapter (1 ... 10).":
Array.from({length: 10}).map( (_, index) => `Chapter ${index + 1}.` );
// Array(10) [ "Chapter 1.", "Chapter 2.", "Chapter 3.", ... ]
(Using _ here as we don't use the value anyway.)

Related

Javascript: Split an array according to a pattern: items 1, 5, 10, then 2, 6, 11, then 3, 7, 12

I am trying to split an array which has a repeating pattern of elements 1, 2, 3, and 4. I want to turn my array [1,2,3,4,5,6,7,8,9,10] into four arrays: [1,5,10], [2,6,11], [3,7,12], and [4,8,13]. I tried using multiples, but the result creates the new arrays in a wrong order. Here is my attempt:
var upload_names_and_ids = [
"Certificat de salaire", //first line is the upload's visible title
"certificat-de-salaire", //second line is the upload's id
"no-info-circle", //third line is the info-circle class
"", //fourth line is the info-circle text
"Allocations Familiales",
"alloc-familiales",
"no-info-circle",
"",
"Courrier Impot (déclaration précédente)",
"courrier-impot",
"info-circle right",
""
];
//Seperate our first array into 4
var upload_names = [];
var upload_ids = [];
var upload_info_circle_class = [];
var upload_info_circle_content = [];
for (var i=0; i<upload_names_and_ids.length; i++){
if (i%4==0) {
upload_info_circle_content.push(upload_names_and_ids[i]);
} else if (i%3==0) {
upload_info_circle_class.push(upload_names_and_ids[i]);
} else if (i%2==0) {
upload_names.push(upload_names_and_ids[i]);
} else {
upload_ids.push(upload_names_and_ids[i]);
}
}
Any help is much appreciated, thank you!
You could take a remainder with index and wanted length.
const
array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16],
length = 4,
result = array.reduce(
(r, v, i) => (r[i % length].push(v), r),
Array.from({ length }, _ => [])
);
console.log(result);
If you like to use predeclared array directly, you could replace this line
Array.from({ length }, _ => [])
with
[upload_names, upload_ids, upload_info_circle_class, upload_info_circle_content]
where the accumulator of Array#reduce keeps the object references.
It's not i%3==0 (which matches 0, 3, 6, …) but i%4==1 (to match 1, 5, 10, …). Same for i%2==0.
I would add a helper sliceN that takes an array and a positive integer. Then returns an array of arrays where the inner arrays are of length n.
sliceN([1,2,3,4,5,6,7,8,9], 3) //=> [[1,2,3], [4,5,6], [7,8,9]]
sliceN([1,2,3,4,5,6], 2) //=> [[1,2], [3,4], [5,6]]
Then also add a helper transpose that transposes a matrix.
transpose([[1,2,3], [4,5,6], [7,8,9]]) //=> [[1,4,7], [2,5,8], [3,6,9]]
transpose([[1,2], [3,4], [5,6]]) //=> [[1,3,5], [2,4,6]]
With these two helpers you can create the wanted result with ease.
const upload_names_and_ids = [
"Certificat de salaire", //first line is the upload's visible title
"certificat-de-salaire", //second line is the upload's id
"no-info-circle", //third line is the info-circle class
"", //fourth line is the info-circle text
"Allocations Familiales",
"alloc-familiales",
"no-info-circle",
"",
"Courrier Impot (déclaration précédente)",
"courrier-impot",
"info-circle right",
""
];
const [
upload_names,
upload_ids,
upload_info_circle_class,
upload_info_circle_content,
] = transpose(sliceN(upload_names_and_ids, 4));
console.log(upload_names);
console.log(upload_ids);
console.log(upload_info_circle_class);
console.log(upload_info_circle_content);
function sliceN(array, n) {
const slices = [];
for (let i = 0; i < array.length; i += n) {
slices.push(array.slice(i, i + n));
}
return slices;
}
function transpose(rows) {
if (rows.length == 0) return [];
const columns = rows[0].map(cell => Array.of(cell));
for (let iRow = 1; iRow < rows.length; iRow += 1) {
for (let iCol = 0; iCol < columns.length; iCol += 1) {
columns[iCol].push(rows[iRow][iCol]);
}
}
return columns;
}
If you are already use a library with helper functions chances are that one or both of these data transforming methods are present. sliceN can often be found as something with split, slice or chunk in the name. transpose is very specific and if present will probably be present under the same name.
As an example Ramda offers both these methods.
R.transpose(R.splitEvery(4, upload_names_and_ids))

Fill Array with null except last index

I need to find a way to fill an Array with a specific amount of nulls and only replace the last value with a specific number.
My idea would to create an empty Array, set Array.length = desiredLength and set Array[lastElement] = value.
But how to fill the rest?
Example:
Input: Array should have a length of five and last value should be 123
Output: [null, null, null, null, 123]
You could fill the array with expected length minus 1 elements of null, spread that, and finally complemented with the last which is your expected element
Below demo should help you
const length = 5
const lastElem = 123
const res = [...Array(length - 1).fill(null), lastElem]
console.log(res)
Try
array.fill(null, 0, array.length - 1)
And then
array[array.length - 1] = 123
Perhaps
const arr = new Array(4).fill(null)
arr.push(123)
console.log(JSON.stringify(arr))
Using Array.from()
const len = 5
const last = 123
const arr = Array.from({ length: len}, (_, i) => i < len - 1 ? null : last)
console.log(arr)
You can also dynamically make a new array using Array.from or Array.apply, and either use the bult in map function for Array.from or call .map after Array.apply
ES6:
var filled=Array.from(
{length: 5},
(x,i, ar) => i < ar.length - 1 ? null : 123
)
ES5
var filled= Array.apply(0, {length: 5})
.map(function (x, i, ar) {
return i < ar.length -1 ? null : 123
})
use new Array() and Array.fill
function createNullFilledArray(arrayLength, lastValue) {
var arr = (new Array(arrayLength)).fill(null, 0, arrayLength - 1);
arr[arrayLength - 1] = lastValue;
return arr;
}
var outPut = createNullFilledArray(10, 123);
console.log(outPut);

how do i split numbers in a array ? javascript

Im trying to split all the numbers in a array:
var array_code = [116,101,120,116];
So i want the result to look like this: [1,1,6,1,0,1,1,2,0,1,1,6]
the code im working on right now looks like this:
var array_gesplit = new Array;
for(var i=0; i< array_code.length; i++){
console.log(array_code[i])
while (array_code[i]) {
array_gesplit.push(array_code[i] % 10 );
array_code[i] = Math.floor(array_code[i]/10);
}
}
The result im getting from this is:
[
6, 1, 1, 1,
0, 1, 0, 2,
1, 6, 1, 1
]
Who can help me ?
You can use Array.from() method for this:
var array_code = [116,101,120,116];
var result = Array.from(array_code.join(''), Number)
console.log(result)
Explanation:
array_code.join('') creates a string like "116101120116"
Array.from('116101120116') on this string results in new Array of strings like:
["1", "1", "6", "1", "0", "1", "1", "2", "0", "1", "1", "6"]
We can also use Array.from() with map function, so that we can convert all these string values to Number in one line like:
Array.from(array_code.join(''), x => Number(x))
Or, just Array.from(array_code.join(''), Number)
The above logic result is the required output.
You can use flatMap() and convert number to string and use built-in split() method.
var array_code = [116,101,120,116];
const res = array_code.flatMap(x => x.toString().split('').map(Number));
console.log(res)
You could take strings and map numbers.
var code = [116, 101, 120, 116],
result = code.flatMap(v => Array.from(v.toString(), Number));
console.log(result);
Here's a hack by using some details of the JavaScript language:
var array_code = [116, 101, 120, 116];
var array_string = JSON.stringify(array_code);
var array_parts = [].slice.call(array_string);
var parts = array_parts.slice(1, -1); // get rid of the square brackets
console.log(parts);

How to convert a string of numbers to an array of numbers?

I have below string -
var a = "1,2,3,4";
when I do -
var b = a.split(',');
I get b as ["1", "2", "3", "4"]
can I do something to get b as [1, 2, 3, 4] ?
You can use Array.map to convert each element into a number.
var a = "1,2,3,4";
var b = a.split(',').map(function(item) {
return parseInt(item, 10);
});
Check the Docs
Or more elegantly as pointed out by User: thg435
var b = a.split(',').map(Number);
Where Number() would do the rest:check here
Note: For older browsers that don't support map, you can add an implementation yourself like:
Array.prototype.map = Array.prototype.map || function(_x) {
for(var o=[], i=0; i<this.length; i++) {
o[i] = _x(this[i]);
}
return o;
};
My 2 cents for golfers:
b="1,2,3,4".split`,`.map(x=>+x)
backquote is string litteral so we can omit the parenthesis (because of the nature of split function) but it is equivalent to split(','). The string is now an array, we just have to map each value with a function returning the integer of the string so x=>+x (which is even shorter than the Number function (5 chars instead of 6)) is equivalent to :
function(x){return parseInt(x,10)}// version from techfoobar
(x)=>{return parseInt(x)} // lambda are shorter and parseInt default is 10
(x)=>{return +x} // diff. with parseInt in SO but + is better in this case
x=>+x // no multiple args, just 1 function call
I hope it is a bit more clear.
This is very simple.Such as:
["1", "2", "3", "4"].map(i=>Number(i))
you can run the demo.
let result = ["1", "2", "3", "4"].map(i=>Number(i));
console.log(result);
Array.from() for details go to MDN
let a = "1,2,3,4";
let b = Array.from(a.split(','),Number);
or
let c = ["1", "2", "3", "4"].map(Number);
b and c is an array of numbers.
demonstration:
let a = "1,2,3,4";
let b = Array.from(a.split(','),Number);
let c = ["1", "2", "3", "4"].map(Number);
console.log(`b: ${b}, c: ${c}`);
Map it to integers:
a.split(',').map(function(i){
return parseInt(i, 10);
})
map looks at every array item, passes it to the function provided and returns an array with the return values of that function. map isn't available in old browsers, but most libraries like jQuery or underscore include a cross-browser version.
Or, if you prefer loops:
var res = a.split(",");
for (var i=0; i<res.length; i++)
{
res[i] = parseInt(res[i], 10);
}
+string will try to change the string to a number. Then use Array.map function to change every element.
"1,2,3,4".split(',').map(function(el){ return +el;});
A more shorter solution: map and pass the arguments to Number:
var a = "1,2,3,4";
var b = a.split(',');
console.log(b);
var c = b.map(Number);
console.log(c);
One liner
Array.from(a.split(','), Number)
There's no need to use lambdas and/or give radix parameter to parseInt, just use parseFloat or Number instead.
Reasons:
It's working:
var src = "1,2,5,4,3";
var ids = src.split(',').map(parseFloat); // [1, 2, 5, 4, 3]
var obj = {1: ..., 3: ..., 4: ..., 7: ...};
var keys= Object.keys(obj); // ["1", "3", "4", "7"]
var ids = keys.map(parseFloat); // [1, 3, 4, 7]
var arr = ["1", 5, "7", 11];
var ints= arr.map(parseFloat); // [1, 5, 7, 11]
ints[1] === "5" // false
ints[1] === 5 // true
ints[2] === "7" // false
ints[2] === 7 // true
It's shorter.
It's a tiny bit quickier and takes advantage of cache, when parseInt-approach - doesn't:
// execution time measure function
// keep it simple, yeah?
> var f = (function (arr, c, n, m) {
var i,t,m,s=n();
for(i=0;i++<c;)t=arr.map(m);
return n()-s
}).bind(null, "2,4,6,8,0,9,7,5,3,1".split(','), 1000000, Date.now);
> f(Number) // first launch, just warming-up cache
> 3971 // nice =)
> f(Number)
> 3964 // still the same
> f(function(e){return+e})
> 5132 // yup, just little bit slower
> f(function(e){return+e})
> 5112 // second run... and ok.
> f(parseFloat)
> 3727 // little bit quicker than .map(Number)
> f(parseFloat)
> 3737 // all ok
> f(function(e){return parseInt(e,10)})
> 21852 // awww, how adorable...
> f(function(e){return parseInt(e)})
> 22928 // maybe, without '10'?.. nope.
> f(function(e){return parseInt(e)})
> 22769 // second run... and nothing changes.
> f(Number)
> 3873 // and again
> f(parseFloat)
> 3583 // and again
> f(function(e){return+e})
> 4967 // and again
> f(function(e){return parseInt(e,10)})
> 21649 // dammit 'parseInt'! >_<
Notice: In Firefox parseInt works about 4 times faster, but still slower than others. In total: +e < Number < parseFloat < parseInt
As a variant you can use combiantion _.map and _.ary methods from the lodash library. Whole transformation will be a more compact. Here is example from the official documentation:
_.map(['6', '8', '10'], _.ary(parseInt, 1));
// → [6, 8, 10]
Use Array.from for this, Try this:
let b = ["1", "2", "3", "4"];
b = Array.from(b,Number);
console.log(b);
The underscore js way -
var a = "1,2,3,4",
b = a.split(',');
//remove falsy/empty values from array after split
b = _.compact(b);
//then Convert array of string values into Integer
b = _.map(b, Number);
console.log('Log String to Int conversion #b =', b);
Matt Zeunert's version with use arraw function (ES6)
const nums = a.split(',').map(x => parseInt(x, 10));
This works amazing if you need to convert an array of strings to numbers.
const numbers = arr => arr.map(Number);
numbers(['1', '2', '3','4']); // [1, 2, 3, 4]
Since all the answers allow NaN to be included, I thought I'd add that if you want to quickly cast an array of mixed values to numbers you can do.
var a = "1,2,3,4,foo,bar";
var b = a.split(',');
var result = b.map(_=>_|0) // Floors the number (32-bit signed integer) so this wont work if you need all 64 bits.
// or b.map(_=>_||0) if you know your array is just numbers but may include NaN.
You can use JSON.parse, adding brakets to format Array
const a = "1,2,3,4";
const myArray = JSON.parse(`[${a}]`)
console.log(myArray)
console.info('pos 2 = ', myArray[2])
You can transform array of strings to array of numbers in one line:
const arrayOfNumbers = arrayOfStrings.map(e => +e);
let ar = [ '682', '874', '906', '11168', '73714',
'74377', '74034', '138860', '138891', '139161', '139562',
'139733', '139560', '74049', '139759', '139934', '140104',
'141335', '141356', '141334', '141337', '141360', '141358',
'141365', '141419', '143333', '151477', '147342', '141355',
'167847', '192141', '196760', '191687', '197351', '197055',
'198852', '198731', '198816', '199034', '200053', '199226',
'217818', '200055', '222039', '230533', '230530', '231127',
'222042', '231100', '236171', '236913', '236980', '237015',
'237016', '237052', '237551', '237560', '237590', '237637',
'237733', '237731', '237655', '238890', '238910', '238837',
'238926', '238972', '238925', '239755', '239696', '239898',
'240037', '239909', '240036', '240082', '240097', '240526',
'240770', '678151', '678950', '678985'];
let arry=[]
ar.map(arr=>{
arry.push(parseInt(arr))
});
console.log(arry);

Remove multiple elements from array in Javascript/jQuery

I have two arrays. The first array contains some values while the second array contains indices of the values which should be removed from the first array. For example:
var valuesArr = new Array("v1","v2","v3","v4","v5");
var removeValFromIndex = new Array(0,2,4);
I want to remove the values present at indices 0,2,4 from valuesArr. I thought the native splice method might help so I came up with:
$.each(removeValFromIndex,function(index,value){
valuesArr.splice(value,1);
});
But it didn't work because after each splice, the indices of the values in valuesArr were different. I could solve this problem by using a temporary array and copying all values to the second array, but I was wondering if there are any native methods to which we can pass multiple indices at which to remove values from an array.
I would prefer a jQuery solution. (Not sure if I can use grep here)
There's always the plain old for loop:
var valuesArr = ["v1","v2","v3","v4","v5"],
removeValFromIndex = [0,2,4];
for (var i = removeValFromIndex.length -1; i >= 0; i--)
valuesArr.splice(removeValFromIndex[i],1);
Go through removeValFromIndex in reverse order and you can .splice() without messing up the indexes of the yet-to-be-removed items.
Note in the above I've used the array-literal syntax with square brackets to declare the two arrays. This is the recommended syntax because new Array() use is potentially confusing given that it responds differently depending on how many parameters you pass in.
EDIT: Just saw your comment on another answer about the array of indexes not necessarily being in any particular order. If that's the case just sort it into descending order before you start:
removeValFromIndex.sort(function(a,b){ return b - a; });
And follow that with whatever looping / $.each() / etc. method you like.
I suggest you use Array.prototype.filter
var valuesArr = ["v1","v2","v3","v4","v5"];
var removeValFrom = [0, 2, 4];
valuesArr = valuesArr.filter(function(value, index) {
return removeValFrom.indexOf(index) == -1;
})
Here is one that I use when not going with lodash/underscore:
while(IndexesToBeRemoved.length) {
elements.splice(IndexesToBeRemoved.pop(), 1);
}
Not in-place but can be done using grep and inArray functions of jQuery.
var arr = $.grep(valuesArr, function(n, i) {
return $.inArray(i, removeValFromIndex) ==-1;
});
alert(arr);//arr contains V2, V4
check this fiddle.
A simple and efficient (linear complexity) solution using filter and Set:
const valuesArr = ['v1', 'v2', 'v3', 'v4', 'v5'];
const removeValFromIndex = [0, 2, 4];
const indexSet = new Set(removeValFromIndex);
const arrayWithValuesRemoved = valuesArr.filter((value, i) => !indexSet.has(i));
console.log(arrayWithValuesRemoved);
The great advantage of that implementation is that the Set lookup operation (has function) takes a constant time, being faster than nevace's answer, for example.
This works well for me and work when deleting from an array of objects too:
var array = [
{ id: 1, name: 'bob', faveColor: 'blue' },
{ id: 2, name: 'jane', faveColor: 'red' },
{ id: 3, name: 'sam', faveColor: 'blue' }
];
// remove people that like blue
array.filter(x => x.faveColor === 'blue').forEach(x => array.splice(array.indexOf(x), 1));
There might be a shorter more effecient way to write this but this does work.
It feels necessary to post an answer with O(n) time :). The problem with the splice solution is that due to the underlying implementation of array being literally an array, each splice call will take O(n) time. This is most pronounced when we setup an example to exploit this behavior:
var n = 100
var xs = []
for(var i=0; i<n;i++)
xs.push(i)
var is = []
for(var i=n/2-1; i>=0;i--)
is.push(i)
This removes elements starting from the middle to the start, hence each remove forces the js engine to copy n/2 elements, we have (n/2)^2 copy operations in total which is quadratic.
The splice solution (assuming is is already sorted in decreasing order to get rid of overheads) goes like this:
for(var i=0; i<is.length; i++)
xs.splice(is[i], 1)
However, it is not hard to implement a linear time solution, by re-constructing the array from scratch, using a mask to see if we copy elements or not (sort will push this to O(n)log(n)). The following is such an implementation (not that mask is boolean inverted for speed):
var mask = new Array(xs.length)
for(var i=is.length - 1; i>=0; i--)
mask[is[i]] = true
var offset = 0
for(var i=0; i<xs.length; i++){
if(mask[i] === undefined){
xs[offset] = xs[i]
offset++
}
}
xs.length = offset
I ran this on jsperf.com and for even n=100 the splice method is a full 90% slower. For larger n this difference will be much greater.
I find this the most elegant solution:
const oldArray = [1, 2, 3, 4, 5]
const removeItems = [1, 3, 5]
const newArray = oldArray.filter((value) => {
return !removeItems.includes(value)
})
console.log(newArray)
output:
[2, 4]
or even shorter:
const newArray = oldArray.filter(v => !removeItems.includes(v))
function filtermethod(element, index, array) {
return removeValFromIndex.find(index)
}
var result = valuesArr.filter(filtermethod);
MDN reference is here
In pure JS you can loop through the array backwards, so splice() will not mess up indices of the elements next in the loop:
for (var i = arr.length - 1; i >= 0; i--) {
if ( yuck(arr[i]) ) {
arr.splice(i, 1);
}
}
A simple solution using ES5. This seems more appropriate for most applications nowadays, since many do no longer want to rely on jQuery etc.
When the indexes to be removed are sorted in ascending order:
var valuesArr = ["v1", "v2", "v3", "v4", "v5"];
var removeValFromIndex = [0, 2, 4]; // ascending
removeValFromIndex.reverse().forEach(function(index) {
valuesArr.splice(index, 1);
});
When the indexes to be removed are not sorted:
var valuesArr = ["v1", "v2", "v3", "v4", "v5"];
var removeValFromIndex = [2, 4, 0]; // unsorted
removeValFromIndex.sort(function(a, b) { return b - a; }).forEach(function(index) {
valuesArr.splice(index, 1);
});
Quick ES6 one liner:
const valuesArr = new Array("v1","v2","v3","v4","v5");
const removeValFromIndex = new Array(0,2,4);
const arrayWithValuesRemoved = valuesArr.filter((value, i) => removeValFromIndex.includes(i))
If you are using underscore.js, you can use _.filter() to solve your problem.
var valuesArr = new Array("v1","v2","v3","v4","v5");
var removeValFromIndex = new Array(0,2,4);
var filteredArr = _.filter(valuesArr, function(item, index){
return !_.contains(removeValFromIndex, index);
});
Additionally, if you are trying to remove items using a list of items instead of indexes, you can simply use _.without(), like so:
var valuesArr = new Array("v1","v2","v3","v4","v5");
var filteredArr = _.without(valuesArr, "V1", "V3");
Now filteredArr should be ["V2", "V4", "V5"]
You can correct your code by replacing removeValFromIndex with removeValFromIndex.reverse(). If that array is not guaranteed to use ascending order, you can instead use removeValFromIndex.sort(function(a, b) { return b - a }).
Here's one possibility:
valuesArr = removeValFromIndex.reduceRight(function (arr, it) {
arr.splice(it, 1);
return arr;
}, valuesArr.sort(function (a, b) { return b - a }));
Example on jsFiddle
MDN on Array.prototype.reduceRight
filter + indexOf (IE9+):
function removeMany(array, indexes) {
return array.filter(function(_, idx) {
return indexes.indexOf(idx) === -1;
});
});
Or with ES6 filter + find (Edge+):
function removeMany(array, indexes = []) {
return array.filter((_, idx) => indexes.indexOf(idx) === -1)
}
Here's a quickie.
function removeFromArray(arr, toRemove){
return arr.filter(item => toRemove.indexOf(item) === -1)
}
const arr1 = [1, 2, 3, 4, 5, 6, 7]
const arr2 = removeFromArray(arr1, [2, 4, 6]) // [1,3,5,7]
Try this
var valuesArr = new Array("v1", "v2", "v3", "v4", "v5");
console.info("Before valuesArr = " + valuesArr);
var removeValFromIndex = new Array(0, 2, 4);
valuesArr = valuesArr.filter((val, index) => {
return !removeValFromIndex.includes(index);
})
console.info("After valuesArr = " + valuesArr);
Sounds like Apply could be what you are looking for.
maybe something like this would work?
Array.prototype.splice.apply(valuesArray, removeValFromIndexes );
var valuesArr = new Array("v1","v2","v3","v4","v5");
var removeValFromIndex = new Array(0,2,4);
console.log(valuesArr)
let arr2 = [];
for (let i = 0; i < valuesArr.length; i++){
if ( //could also just imput this below instead of index value
valuesArr[i] !== valuesArr[0] && // "v1" <--
valuesArr[i] !== valuesArr[2] && // "v3" <--
valuesArr[i] !== valuesArr[4] // "v5" <--
){
arr2.push(valuesArr[i]);
}
}
console.log(arr2);
This works. However, you would make a new array in the process. Not sure if thats would you want or not, but technically it would be an array containing only the values you wanted.
You can try Lodash js library functions (_.forEach(), _.remove()). I was using this technique to remove multiple rows from the table.
let valuesArr = [
{id: 1, name: "dog"},
{id: 2, name: "cat"},
{id: 3, name: "rat"},
{id: 4, name: "bat"},
{id: 5, name: "pig"},
];
let removeValFromIndex = [
{id: 2, name: "cat"},
{id: 5, name: "pig"},
];
_.forEach(removeValFromIndex, (indi) => {
_.remove(valuesArr, (item) => {
return item.id === indi.id;
});
})
console.log(valuesArr)
/*[
{id: 1, name: "dog"},
{id: 3, name: "rat"},
{id: 4, name: "bat"},
];*/
Don't forget to clone (_.clone(valuesArr) or [...valuesArr]) before mutate your array
You could try and use delete array[index] This won't completely remove the element but rather sets the value to undefined.
removeValFromIndex.forEach(function(toRemoveIndex){
valuesArr.splice(toRemoveIndex,1);
});
For Multiple items or unique item:
I suggest you use Array.prototype.filter
Don't ever use indexOf if you already know the index!:
var valuesArr = ["v1","v2","v3","v4","v5"];
var removeValFrom = [0, 2, 4];
valuesArr = valuesArr.filter(function(value, index) {
return removeValFrom.indexOf(index) == -1;
}); // BIG O(N*m) where N is length of valuesArr and m is length removeValFrom
Do:
with Hashes... using Array.prototype.map
var valuesArr = ["v1","v2","v3","v4","v5"];
var removeValFrom = {};
([0, 2, 4]).map(x=>removeValFrom[x]=1); //bild the hash.
valuesArr = valuesArr.filter(function(value, index) {
return removeValFrom[index] == 1;
}); // BIG O(N) where N is valuesArr;
You could construct a Set from the array and then create an array from the set.
const array = [1, 1, 2, 3, 5, 5, 1];
const uniqueArray = [...new Set(array)];
console.log(uniqueArray); // Result: [1, 2, 3, 5]

Categories

Resources