A better way to splice an array into an array in javascript - javascript

Is there a better way than this to splice an array into another array in javascript
var string = 'theArray.splice('+start+', '+number+',"'+newItemsArray.join('","')+'");';
eval(string);

You can use apply to avoid eval:
var args = [start, number].concat(newItemsArray);
Array.prototype.splice.apply(theArray, args);
The apply function is used to call another function, with a given context and arguments, provided as an array, for example:
If we call:
var nums = [1,2,3,4];
Math.min.apply(Math, nums);
The apply function will execute:
Math.min(1,2,3,4);

UPDATE: ES6 version
If you're coding in ES6, you can use the "spread operator" (...).
array.splice(index, 0, ...arrayToInsert);
To learn more about the spread operator see the MDN documentation.
The 'old' ES5 way
If you wrap the top answer into a function you get this:
function insertArrayAt(array, index, arrayToInsert) {
Array.prototype.splice.apply(array, [index, 0].concat(arrayToInsert));
}
You would use it like this:
var arr = ["A", "B", "C"];
insertArrayAt(arr, 1, ["x", "y", "z"]);
alert(JSON.stringify(arr)); // output: A, x, y, z, B, C
You can check it out in this jsFiddle: http://jsfiddle.net/luisperezphd/Wc8aS/

This question is really old, but with ES6, there's a simpler way to do this using the spread operator:
sourceArray.splice(index, 0, ...insertedArray)
If you're using uncompiled javascript in the browser, be sure to check if it's supported in your target browser at https://kangax.github.io/compat-table/es6/#test-spread_(...)_operator.
Also, this may be slightly off topic, but if you don't want or need to modify the original array, but could use a new array instead, consider this approach:
mergedArray = sourceArray.slice(0, index).concat(insertedArray, sourceArray.slice(index))

You can also add such a function to the Array prototype, if you want something that is almost identical to the splice method. E.g.
Array.prototype.spliceArray = function(index, n, array) {
return Array.prototype.splice.apply(this, [index, n].concat(array));
}
Then usage would simply be:
var array = ["A","B","C","","E","F"];
array.splice(3,1,"D");
// array is ["A","B","C","D","E","F"]
array.spliceArray(3,3,["1","2","3"]);
// array is ["A","B","C","1","2","3"]
See it in action here: http://jsfiddle.net/TheMadDeveloper/knv2f8bb/1/
Some notes:
The splice function modifies the array directly, but returns the an array of elements that were removed... not the spliced array.
While it's normally not recommended to extend core javascript classes, this is relatively benign with most standard frameworks.
Extending Array won't work in cases where specialized array classes are used, such as an ImageData data Uint8ClampedArray.

The answers above that involve splice.apply and insert the array in a one liner will blow up the stack in a stack overflow for large array.
See example here:
http://jsfiddle.net/gkohen/u49ku99q/
You might have to slice and and push each item of the inserted and remaining part of the original array for it to work.
See fiddle: http://jsfiddle.net/gkohen/g9abppgy/26/
Array.prototype.spliceArray = function(index, insertedArray) {
var postArray = this.splice(index);
inPlacePush(this, insertedArray);
inPlacePush(this, postArray);
function inPlacePush(targetArray, pushedArray) {
// Not using forEach for browser compatability
var pushedArrayLength = pushedArray.length;
for (var index = 0; index < pushedArrayLength; index++) {
targetArray.push(pushedArray[index]);
}
}
}

There are a lot of clever answers here, but the reason you use splice is so that it puts the elements into the current array without creating another. If you have to create an array to concat() against so you can use apply() then you're creating 2 additional trash arrays! Sorta defeats the whole purpose of writing esoteric Javascript. Besides if you don't care about that memory usage stuff (and you should) just dest = src1.concat(src2); it is infinitely more readable. So here's is my smallest number of lines while staying efficient answer.
for( let item of src ) dest.push( item );
Or if you'd like to polyfill it and have a little better browser support back:
src.forEach( function( x ) { dest.push(x); });
I'm sure the first is more performant (it's a word ;), but not supported in all browsers out there in the wild.

If you don't want to concatenate inserting items to first two parameters of Array.splice(),
an elegant way is to use Function.bind() and Function.apply() together.
theArray.splice.bind(null, startIndex, deleteCount).apply(newItemsArray);

I wanted to have a function which would take only part of the source array so I have mine slightly different
based off CMS's answer
function spliceArray(array, index, howmany, source, start, end) {
var arguments;
if( source !== undefined ){
arguments = source.slice(start, end);
arguments.splice(0,0, index, howmany);
} else{
arguments = [index, howmany];
}
return Array.prototype.splice.apply(array, arguments)
}
Array.prototype.spliceArray = function(index, howmany, source, start, end) {
return spliceArray(this, index, howmany, source, start, end);
}
You can see it at: https://jsfiddle.net/matthewvukomanovic/nx858uz5/

Related

In ES5 Javascript, how do I add an item to an array and return the new array immediately, without using concat?

I often find myself in the situation where I want to, in a single (atomic) operation, add an item to an array and return that new array.
['a', 'b'].push('c');
won't work as it returns the new length.
I know the following code works
['a', 'b'].concat(['c']);
But I find it ugly code (combining two arrays just to add a single item to the end of the first array).
I can't use Array.splice() as it modifies the original array (and returns the removed items). Array.slice() does return a shallow copy but you can't add new items.
ES6
I'm aware that in es6 you can use
[...['a', 'b'], 'c']
But I'm looking for an es5 solution
Lodash
I'm okay in using lodash
Just to be clear
I'm aware that this can be achieved in several different ways (like the Array.concat() method above), but I'm looking for an intuitive simple piece of code, which doesn't "misuses" other operators
I know the following code works ['a', 'b'].concat(['c']); But I find
it ugly code (combining two arrays just to add a single item to the
end of the first array).
The concat() method can be given a single (or multiple) values without the need of encapsulating the value(s) in an array first, for example:
['a', 'b'].concat('c'); // instead of .concat(['c']);
From MDN (my emphasis):
Arrays and/or values to concatenate into a new array.
Besides from that there are limited options without using extension and existing methods.
Example on how to extend the Array (this will return current array though):
Array.prototype.append = function(item) {
this.push(item);
return this
};
var a = [1, 2, 3];
console.log(a.append(4))
Optionally create a simple function as #torazaburo suggests, which can take array and item as argument:
function append(arr, item) {
arr.push(item);
return arr;
}
or using concat():
function append(arr, item) {
return arr.concat(item)
}
I can offer two methods for Array.prototype.insert() which will allow you insert single or multiple elements starting from any index within the array.
1) mutates the array it's called upon and returns it
Array.prototype.insert = function(i,...rest){
this.splice(i,0,...rest)
return this
}
var a = [3,4,8,9];
console.log(JSON.stringify(a.insert(2,5,6,7)));
ES5 compliant version of the above snippet.
Array.prototype.insert = function(i){
this.splice.apply(this,[i,0].concat(Array.prototype.slice.call(arguments,1)));
return this;
};
2) Not mutates the array it's called upon and returns a new one
Array.prototype.insert = function(i,...rest){
return this.slice(0,i).concat(rest,this.slice(i));
}
var a = [3,4,8,9],
b = a.insert(2,5,6,7);
console.log(JSON.stringify(a));
console.log(JSON.stringify(b));
ES5 compliant version of the above snippet.
Array.prototype.insert = function(i){
return this.slice(0,i).concat(Array.prototype.slice.call(arguments,1),this.slice(i));
}

Array.prototype.map() and Array.prototype.forEach()

I've an array (example array below) -
a = [{"name":"age","value":31},
{"name":"height (inches)","value":62},
{"name":"location","value":"Boston, MA"},
{"name":"gender","value":"male"}];
I want to iterate through this array of objects and produce a new Object (not specifically reduce).
I've these two approaches -
a = [{"name":"age","value":31},
{"name":"height (inches)","value":62},
{"name":"location","value":"Boston, MA"},
{"name":"gender","value":"male"}];
// using Array.prototype.map()
b = a.map(function(item){
var res = {};
res[item.name] = item.value;
return res;
});
console.log(JSON.stringify(b));
var newObj = [];
// using Array.prototype.forEach()
a.forEach(function(d){
var obj = {};
obj[d.name] = d.value;
newObj.push(obj)
});
console.log(JSON.stringify(newObj))
Is it not right to just use either one for this sort of operations?
Also, I'd like to understand the use case scenarios where one will be preferred over the other? Or should I just stick to for-loop?
As you've already discussed in the comments, there's no outright wrong answer here. Aside from some rather fine points of performance, this is a style question. The problem you are solving can be solved with a for loop, .forEach(), .reduce(), or .map().
I list them in that order deliberately, because each one of them could be re-implemented using anything earlier in the list. You can use .reduce() to duplicate .map(), for instance, but not the reverse.
In your particular case, unless micro-optimizations are vital to your domain, I'd make the decision on the basis of readability and code-maintenance. On that basis, .map() does specifically and precisely what you're after; someone reading your code will see it and know you're consuming an array to produce another array. You could accomplish that with .forEach() or .reduce(), but because those are capable of being used for more things, someone has to take that extra moment to understand what you ARE using them for. .map() is the call that's most expressive of your intent.
(Yes, that means in essence prioritizing efficiency-of-understanding over efficiency-of-execution. If the code isn't part of a performance bottleneck in a high-demand application, I think that's appropriate.)
You asked about scenarios where another might be preferred. In this case, .map() works because you're outputting an array, and your output array has the same length as your input array. (Again; that's what .map() does). If you wanted to output an array, but you might need to produce two (or zero) elements of output for a single element of input, .map() would be out and I'd probably use .reduce(). (Chaining .filter().map() would also be a possibility for the 'skip some input elements' case, and would be pretty legible)
If you wanted to split the contents of the input array into multiple output arrays, you could do that with .reduce() (by encapsulating all of them as properties of a single object), but .forEach() or the for loop would look more natural to me.
First, either of those will work and with your example there's no reason not to use which ever is more comfortable for your development cycle. I would probably use map since that is what is for; to create "a new array with the results of calling a provided function on every element in this array."
However, are you asking which is the absolute fastest? Then neither of those; the fastest by 2.5-3x will be a simple for-loop (see http://jsperf.com/loop-vs-map-vs-foreach for a simple comparison):
var newObj = [];
for (var i = 0, item; item = a[i]; i++) {
var obj = {};
obj[item.name] = item.value;
newObj.push(obj);
});
console.log(JSON.stringify(newObj));

javascript check existence of elements of 1 array inside the other

For searching elements of one array inside the other, one may use the indexOf() on the target of search and run a loop on the other array elements and in each step check existence. This is trivial and my knowledge on Javascript is too. Could any one please suggest a more efficient way? Maybe even a built-in method of the language could help? Although I couldn't hit to such a method using google.
You can use Array.filter() internally and implement a function on Array's prototype which returns elements which are common to both.
Array.prototype.common = function(a) {
return this.filter(function(i) {
return a.indexOf(i) >= 0;
});
};
alert([1,2,3,4,5].common([4,5,6])); // "4, 5"
Again as you mention in your post, this logic also works by taking each element and checking whether it exists in the other.
A hair more efficient way is convert one of the arrays into a hash table and then loop through the second one, checking the presence of elements at O(1) time:
a = [1,2,3,4,5]
b = [1,7,3,8,5]
map = {}
a.forEach(function(x) { map[x] = 1 })
intersection = b.filter(function(x) { return map[x] === 1 })
document.write(JSON.stringify(intersection))
This only works if elements in question are primitives. For arrays of objects you have to resort to the indexOf method.
ES6 ("Harmony") does support Set, but strangely not set operations (union, intersection etc), so these should be coded by hand:
// Firefox only
a = [1,2,3,4,5]
b = [1,7,3,8,5]
sa = new Set(a)
sb = new Set(b)
sa.forEach(function(x) {
if (!sb.has(x))
sa.delete(x);
});
document.write(uneval([...sa]))
JavaScript's arrays don't have a method that does intersections. Various libraries provide methods to do it (by looping the array as you describe), including Underscore and PrototypeJS (and others, I'm sure).

How to pass an array as argument to a function in javascript?

I'm trying to make helper functions to make use of the Google Analytics API, and I have a simple problem building strings. The scenario is, I have to apply a filter, and there may be n number of filters (a nominal amount, not more than 128 anyhow). I wanted to write a function which can take in the n strings and combine them with comma-separation in between.
I don't know if the number of arguments can be variable in javascript, and if it can take arrays as arguments in javascript (I am a newbie to JS), but I see no difference as variables are simply var and there is no datatype anywhere in JS (I come from a C++/Java background and find it confusing as it is). So I tried passing an array as an argument to a function so that the no. of things I can work with can be dynamic, decided by the elements in the array.
When I started searching for solutions, I came across this page. After that I recently came across this thread which also refers the same link and the format they have provided does me no good.
For the sake of clarity, let me provide the function definition I've written.
/**
* Utility method to build a comma-ed string from an array of strings
* for the multiple-condition requests to the GA API
*/
function buildString(strArray)
{
var returnString='';
for(var x in strArray)
returnString+=x+',';
return returnString = returnString.substring(0, returnString.length - 1);
}
And this is how I call it:
buildString.apply(this,[desc(visits),source])
where desc(visits) and source are both strings, so I assumed I'm sending an array of strings. Strangely, both this and null in the apply() call to the buildString function give me "0,1" as the return value.
Please tell me where I'm going wrong. Am I passing the array in a wrong manner? Or is my function definition wrong? Or is there some other simpler way to achieve what I'm trying?
Passing arrays to functions is no different from passing any other type:
var string = buildString([desc(visits), source]);
However, your function is not necessary, since Javascript has a built-in function for concatenating array elements with a delimiter:
var string = someArray.join(',');
You're over complicating things — JavaScript arrays have a built-in join method:
[ desc( visits ), source ].join( ',' );
EDIT: simpler still: the toString method:
[ desc( visits ), source ].toString();
The easiest would be to use the built-in join method:
[desc(visits), source].join(',');
Anyway, your problem was in the for..in loop
Instead of this:
for(var x in strArray){
returnString+=x+',';
}
You should have:
for(var i in strArray){
var x = strArray[i]; //Note this
returnString+=x+',';
}
Because for...in gives back the index/key, not the actual element as foreach does in other languages
Also your call should be:
buildString.call(this,[desc(visits),source]) or just buildString([desc(visits),source])
Cheers
Js argument can be any type and no limit to the number of argument,
But it is recommanded use 3-4 arguments at most, if there are more args, you can pass it as an object or array.
You don't need to worry about the type of args, js will do the job.
For example:
var func1 = function(a) {
console.log(a);
}
func1('good');
func1(1);
func1(['good', 'a', 1]);
func1({name: 'fn1', age: 12});
Anything you like!,
You can even define a function with three arguments, but only pass one is ok!
var func2 = function(a, b, c) {
console.log(a);
}
func2(1);
func2(1, 'good');
func2(1, 'good', 'night', 4);
And default array obj has many build-in func; for example:
var arr = ['good', 'night', 'foo', 'bar']; //define any thing in a array
str = arr.join(','); //you may get 'good,night,foo,bar'
var arr1 = str.split(','); // you may get ['good', 'night', 'foo', 'bar'];

Most efficient way to convert an HTMLCollection to an Array

Is there a more efficient way to convert an HTMLCollection to an Array, other than iterating through the contents of said collection and manually pushing each item into an array?
var arr = Array.prototype.slice.call( htmlCollection )
will have the same effect using "native" code.
Edit
Since this gets a lot of views, note (per #oriol's comment) that the following more concise expression is effectively equivalent:
var arr = [].slice.call(htmlCollection);
But note per #JussiR's comment, that unlike the "verbose" form, it does create an empty, unused, and indeed unusable array instance in the process. What compilers do about this is outside the programmer's ken.
Edit
Since ECMAScript 2015 (ES 6) there is also Array.from:
var arr = Array.from(htmlCollection);
Edit
ECMAScript 2015 also provides the spread operator, which is functionally equivalent to Array.from (although note that Array.from supports a mapping function as the second argument).
var arr = [...htmlCollection];
I've confirmed that both of the above work on NodeList.
A performance comparison for the mentioned methods: http://jsben.ch/h2IFA
not sure if this is the most efficient, but a concise ES6 syntax might be:
let arry = [...htmlCollection]
Edit: Another one, from Chris_F comment:
let arry = Array.from(htmlCollection)
I saw a more concise method of getting Array.prototype methods in general that works just as well. Converting an HTMLCollection object into an Array object is demonstrated below:
[].slice.call( yourHTMLCollectionObject );
And, as mentioned in the comments, for old browsers such as IE7 and earlier, you simply have to use a compatibility function, like:
function toArray(x) {
for(var i = 0, a = []; i < x.length; i++)
a.push(x[i]);
return a
}
I know this is an old question, but I felt the accepted answer was a little incomplete; so I thought I'd throw this out there FWIW.
For a cross browser implementation I'd sugguest you look at prototype.js $A function
copyed from 1.6.1:
function $A(iterable) {
if (!iterable) return [];
if ('toArray' in Object(iterable)) return iterable.toArray();
var length = iterable.length || 0, results = new Array(length);
while (length--) results[length] = iterable[length];
return results;
}
It doesn't use Array.prototype.slice probably because it isn't available on every browser. I'm afraid the performance is pretty bad as there a the fall back is a javascript loop over the iterable.
This works in all browsers including earlier IE versions.
var arr = [];
[].push.apply(arr, htmlCollection);
Since jsperf is still down at the moment, here is a jsfiddle that compares the performance of different methods. https://jsfiddle.net/qw9qf48j/
To convert array-like to array in efficient way we can make use of the jQuery makeArray :
makeArray: Convert an array-like object into a true JavaScript array.
Usage:
var domArray = jQuery.makeArray(htmlCollection);
A little extra:
If you do not want to keep reference to the array object (most of the time HTMLCollections are dynamically changes so its better to copy them into another array, This example pay close attention to performance:
var domDataLength = domData.length //Better performance, no need to calculate every iteration the domArray length
var resultArray = new Array(domDataLength) // Since we know the length its improves the performance to declare the result array from the beginning.
for (var i = 0 ; i < domDataLength ; i++) {
resultArray[i] = domArray[i]; //Since we already declared the resultArray we can not make use of the more expensive push method.
}
What is array-like?
HTMLCollection is an "array-like" object, the array-like objects are similar to array's object but missing a lot of its functionally definition:
Array-like objects look like arrays. They have various numbered
elements and a length property. But that’s where the similarity stops.
Array-like objects do not have any of Array’s functions, and for-in
loops don’t even work!
This is my personal solution, based on the information here (this thread):
var Divs = new Array();
var Elemns = document.getElementsByClassName("divisao");
try {
Divs = Elemns.prototype.slice.call(Elemns);
} catch(e) {
Divs = $A(Elemns);
}
Where $A was described by Gareth Davis in his post:
function $A(iterable) {
if (!iterable) return [];
if ('toArray' in Object(iterable)) return iterable.toArray();
var length = iterable.length || 0, results = new Array(length);
while (length--) results[length] = iterable[length];
return results;
}
If browser supports the best way, ok, otherwise will use the cross browser.
I suppose that calling Array.prototype functions on instances of HTMLCollection is a much better option than converting collections to arrays (e.g.,[...collection] or Array.from(collection)), because in the latter case a collection is unnecessarily implicitly iterated and a new array object is created, and this eats up additional resources. Array.prototype iterating functions can be safely called upon objects with consecutive numeric keys starting from [0] and a length property with a valid number value of such keys' quantity (including, e.g., instances of HTMLCollection and FileList), so it's a reliable way. Also, if there is a frequent need in such operations, an empty array [] can be used for quick access to Array.prototype functions; or a shortcut for Array.prototype can be created instead. A runnable example:
const _ = Array.prototype;
const collection = document.getElementById('ol').children;
alert(_.reduce.call(collection, (acc, { textContent }, i) => {
return acc += `${i+1}) ${textContent}` + '\n';
}, ''));
<ol id="ol">
<li>foo</li>
<li>bar</li>
<li>bat</li>
<li>baz</li>
</ol>
Sometimes, Even You have written code the correct way, But still it doesn't work properly.
var allbuttons = document.getElementsByTagName("button");
console.log(allbuttons);
var copyAllButtons = [];
for (let i = 0; i < allbuttons.length; i++) {
copyAllButtons.push(allbuttons[i]);
}
console.log(copyAllButtons);
you get empty array.
Like, This
HTMLCollection []
[]
Console_javascript
For Solving this problem, You have to add link of javascript file after body tag in html file.
<script src="./script.js"></script>
As you can see below,
html_file
Final Output
HTMLCollection(6) [button.btn.btn-dark.click-me, button.btn.btn-dark.reset, button#b, button#b, button#b, button#b, b: button#b]
(6) [button.btn.btn-dark.click-me, button.btn.btn-dark.reset, button#b, button#b, button#b, button#b]

Categories

Resources