Javascript swap array elements - javascript

Is there any simpler way to swap two elements in an array?
var a = list[x], b = list[y];
list[y] = a;
list[x] = b;

You only need one temporary variable.
var b = list[y];
list[y] = list[x];
list[x] = b;
Edit hijacking top answer 10 years later with a lot of ES6 adoption under our belts:
Given the array arr = [1,2,3,4], you can swap values in one line now like so:
[arr[0], arr[1]] = [arr[1], arr[0]];
This would produce the array [2,1,3,4]. This is destructuring assignment.

If you want a single expression, using native javascript,
remember that the return value from a splice operation
contains the element(s) that was removed.
var A = [1, 2, 3, 4, 5, 6, 7, 8, 9], x= 0, y= 1;
A[x] = A.splice(y, 1, A[x])[0];
alert(A); // alerts "2,1,3,4,5,6,7,8,9"
Edit:
The [0] is necessary at the end of the expression as Array.splice() returns an array, and in this situation we require the single element in the returned array.

According to some random person on Metafilter,
"Recent versions of Javascript allow you to do swaps (among other things) much more neatly:"
[ list[x], list[y] ] = [ list[y], list[x] ];
My quick tests showed that this Pythonic code works great in the version of JavaScript
currently used in "Google Apps Script" (".gs").
Alas, further tests show this code gives a "Uncaught ReferenceError: Invalid left-hand side in assignment." in
whatever version of JavaScript (".js") is used by
Google Chrome Version 24.0.1312.57 m.

This seems ok....
var b = list[y];
list[y] = list[x];
list[x] = b;
Howerver using
var b = list[y];
means a b variable is going to be to be present for the rest of the scope. This can potentially lead to a memory leak. Unlikely, but still better to avoid.
Maybe a good idea to put this into Array.prototype.swap
Array.prototype.swap = function (x,y) {
var b = this[x];
this[x] = this[y];
this[y] = b;
return this;
}
which can be called like:
list.swap( x, y )
This is a clean approach to both avoiding memory leaks and DRY.

Well, you don't need to buffer both values - only one:
var tmp = list[x];
list[x] = list[y];
list[y] = tmp;

You can swap elements in an array the following way:
list[x] = [list[y],list[y]=list[x]][0]
See the following example:
list = [1,2,3,4,5]
list[1] = [list[3],list[3]=list[1]][0]
//list is now [1,4,3,2,5]
Note: it works the same way for regular variables
var a=1,b=5;
a = [b,b=a][0]

This didn't exist when the question was asked, but ES2015 introduced array destructuring, allowing you to write it as follows:
let a = 1, b = 2;
// a: 1, b: 2
[a, b] = [b, a];
// a: 2, b: 1

Consider such a solution without a need to define the third variable:
function swap(arr, from, to) {
arr.splice(from, 1, arr.splice(to, 1, arr[from])[0]);
}
var letters = ["a", "b", "c", "d", "e", "f"];
swap(letters, 1, 4);
console.log(letters); // ["a", "e", "c", "d", "b", "f"]
Note: You may want to add additional checks for example for array length. This solution is mutable so swap function does not need to return a new array, it just does mutation over array passed into.

With numeric values you can avoid a temporary variable by using bitwise xor
list[x] = list[x] ^ list[y];
list[y] = list[y] ^ list[x];
list[x] = list[x] ^ list[y];
or an arithmetic sum (noting that this only works if x + y is less than the maximum value for the data type)
list[x] = list[x] + list[y];
list[y] = list[x] - list[y];
list[x] = list[x] - list[y];

To swap two consecutive elements of array
array.splice(IndexToSwap,2,array[IndexToSwap+1],array[IndexToSwap]);

For two or more elements (fixed number)
[list[y], list[x]] = [list[x], list[y]];
No temporary variable required!
I was thinking about simply calling list.reverse().
But then I realised it would work as swap only when list.length = x + y + 1.
For variable number of elements
I have looked into various modern Javascript constructions to this effect, including Map and map, but sadly none has resulted in a code that was more compact or faster than this old-fashioned, loop-based construction:
function multiswap(arr,i0,i1) {/* argument immutable if string */
if (arr.split) return multiswap(arr.split(""), i0, i1).join("");
var diff = [];
for (let i in i0) diff[i0[i]] = arr[i1[i]];
return Object.assign(arr,diff);
}
Example:
var alphabet = "abcdefghijklmnopqrstuvwxyz";
var [x,y,z] = [14,6,15];
var output = document.getElementsByTagName("code");
output[0].innerHTML = alphabet;
output[1].innerHTML = multiswap(alphabet, [0,25], [25,0]);
output[2].innerHTML = multiswap(alphabet, [0,25,z,1,y,x], [25,0,x,y,z,3]);
<table>
<tr><td>Input:</td> <td><code></code></td></tr>
<tr><td>Swap two elements:</td> <td><code></code></td></tr>
<tr><td>Swap multiple elements: </td> <td><code></code></td></tr>
</table>

what about Destructuring_assignment
var arr = [1, 2, 3, 4]
[arr[index1], arr[index2]] = [arr[index2], arr[index1]]
which can also be extended to
[src order elements] => [dest order elements]

Digest from http://www.greywyvern.com/?post=265
var a = 5, b = 9;
b = (a += b -= a) - b;
alert([a, b]); // alerts "9, 5"

You can swap any number of objects or literals, even of different types, using a simple identity function like this:
var swap = function (x){return x};
b = swap(a, a=b);
c = swap(a, a=b, b=c);
For your problem:
var swap = function (x){return x};
list[y] = swap(list[x], list[x]=list[y]);
This works in JavaScript because it accepts additional arguments even if they are not declared or used. The assignments a=b etc, happen after a is passed into the function.

There is one interesting way of swapping:
var a = 1;
var b = 2;
[a,b] = [b,a];
(ES6 way)

Here's a one-liner that doesn't mutate list:
let newList = Object.assign([], list, {[x]: list[y], [y]: list[x]})
(Uses language features not available in 2009 when the question was posted!)

var a = [1,2,3,4,5], b=a.length;
for (var i=0; i<b; i++) {
a.unshift(a.splice(1+i,1).shift());
}
a.shift();
//a = [5,4,3,2,1];

var arr = [1, 2];
arr.splice(0, 2, arr[1], arr[0]);
console.log(arr); //[2, 1]

Flow
not inplace solution
let swap= (arr,i,j)=> arr.map((e,k)=> k-i ? (k-j ? e : arr[i]) : arr[j]);
let swap= (arr,i,j)=> arr.map((e,k)=> k-i ? (k-j ? e : arr[i]) : arr[j]);
// test index: 3<->5 (= 'f'<->'d')
let a= ["a","b","c","d","e","f","g"];
let b= swap(a,3,5);
console.log(a,"\n", b);
console.log('Example Flow:', swap(a,3,5).reverse().join('-') );
and inplace solution
let swap= (arr,i,j)=> {let t=arr[i]; arr[i]=arr[j]; arr[j]=t; return arr}
// test index: 3<->5 (= 'f'<->'d')
let a= ["a","b","c","d","e","f","g"];
console.log( swap(a,3,5) )
console.log('Example Flow:', swap(a,3,5).reverse().join('-') );
In this solutions we use "flow pattern" which means that swap function returns array as result - this allow to easily continue processing using dot . (like reverse and join in snippets)

Here's a compact version
swaps value at i1 with i2 in arr
arr.slice(0,i1).concat(arr[i2],arr.slice(i1+1,i2),arr[i1],arr.slice(i2+1))

Here is a variation that first checks if the index exists in the array:
Array.prototype.swapItems = function(a, b){
if( !(a in this) || !(b in this) )
return this;
this[a] = this.splice(b, 1, this[a])[0];
return this;
}
It currently will just return this if the index does not exist, but you could easily modify behavior on fail

If you don't want to use temp variable in ES5, this is one way to swap array elements.
var swapArrayElements = function (a, x, y) {
if (a.length === 1) return a;
a.splice(y, 1, a.splice(x, 1, a[y])[0]);
return a;
};
swapArrayElements([1, 2, 3, 4, 5], 1, 3); //=> [ 1, 4, 3, 2, 5 ]

Array.prototype.swap = function(a, b) {
var temp = this[a];
this[a] = this[b];
this[b] = temp;
};
Usage:
var myArray = [0,1,2,3,4...];
myArray.swap(4,1);

Typescript solution that clones the array instead of mutating existing one
export function swapItemsInArray<T>(items: T[], indexA: number, indexB: number): T[] {
const itemA = items[indexA];
const clone = [...items];
clone[indexA] = clone[indexB];
clone[indexB] = itemA;
return clone;
}

If you are not allowed to use in-place swap for some reason, here is a solution with map:
function swapElements(array, source, dest) {
return source === dest
? array : array.map((item, index) => index === source
? array[dest] : index === dest
? array[source] : item);
}
const arr = ['a', 'b', 'c'];
const s1 = swapElements(arr, 0, 1);
console.log(s1[0] === 'b');
console.log(s1[1] === 'a');
const s2 = swapElements(arr, 2, 0);
console.log(s2[0] === 'c');
console.log(s2[2] === 'a');
Here is typescript code for quick copy-pasting:
function swapElements(array: Array<any>, source: number, dest: number) {
return source === dest
? array : array.map((item, index) => index === source
? array[dest] : index === dest
? array[source] : item);
}

For the sake of brevity, here's the ugly one-liner version that's only slightly less ugly than all that concat and slicing above. The accepted answer is truly the way to go and way more readable.
Given:
var foo = [ 0, 1, 2, 3, 4, 5, 6 ];
if you want to swap the values of two indices (a and b); then this would do it:
foo.splice( a, 1, foo.splice(b,1,foo[a])[0] );
For example, if you want to swap the 3 and 5, you could do it this way:
foo.splice( 3, 1, foo.splice(5,1,foo[3])[0] );
or
foo.splice( 5, 1, foo.splice(3,1,foo[5])[0] );
Both yield the same result:
console.log( foo );
// => [ 0, 1, 2, 5, 4, 3, 6 ]
#splicehatersarepunks:)

Swap the first and last element in an array without temporary variable or ES6 swap method [a, b] = [b, a]
[a.pop(), ...a.slice(1), a.shift()]

function moveElement(array, sourceIndex, destinationIndex) {
return array.map(a => a.id === sourceIndex ? array.find(a => a.id === destinationIndex): a.id === destinationIndex ? array.find(a => a.id === sourceIndex) : a )
}
let arr = [
{id: "1",title: "abc1"},
{id: "2",title: "abc2"},
{id: "3",title: "abc3"},
{id: "4",title: "abc4"}];
moveElement(arr, "2","4");

in place swap
// array methods
function swapInArray(arr, i1, i2){
let t = arr[i1];
arr[i1] = arr[i2];
arr[i2] = t;
}
function moveBefore(arr, el){
let ind = arr.indexOf(el);
if(ind !== -1 && ind !== 0){
swapInArray(arr, ind, ind - 1);
}
}
function moveAfter(arr, el){
let ind = arr.indexOf(el);
if(ind !== -1 && ind !== arr.length - 1){
swapInArray(arr, ind + 1, ind);
}
}
// dom methods
function swapInDom(parentNode, i1, i2){
parentNode.insertBefore(parentNode.children[i1], parentNode.children[i2]);
}
function getDomIndex(el){
for (let ii = 0; ii < el.parentNode.children.length; ii++){
if(el.parentNode.children[ii] === el){
return ii;
}
}
}
function moveForward(el){
let ind = getDomIndex(el);
if(ind !== -1 && ind !== 0){
swapInDom(el.parentNode, ind, ind - 1);
}
}
function moveBackward(el){
let ind = getDomIndex(el);
if(ind !== -1 && ind !== el.parentNode.children.length - 1){
swapInDom(el.parentNode, ind + 1, ind);
}
}

Just for the fun of it, another way without using any extra variable would be:
var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9];
// swap index 0 and 2
arr[arr.length] = arr[0]; // copy idx1 to the end of the array
arr[0] = arr[2]; // copy idx2 to idx1
arr[2] = arr[arr.length-1]; // copy idx1 to idx2
arr.length--; // remove idx1 (was added to the end of the array)
console.log( arr ); // -> [3, 2, 1, 4, 5, 6, 7, 8, 9]

Related

Trying to write a inverse version of Javascript's filter method that will work on both arrays and objects

So as the question states, I'm attempting to write a function for which the input can be either an Array or an Object (as well as a callback to test them against).
The desired return value is an Array / Object of the elements (value/key pairs in the case of the Object) that passed the test - but the original Array / Object should be updated to remove those elements.
For example - if you passed in an "isEven" callback function that determines if numbers are even, then the expected results would be:
let a = [1, 2, 3, 4]
reject(a)
//Output:
[2, 4]
console.log(a);
//expected output
[1, 3]
So far I've been trying to write an conditional scenario based on Array.isArray(input), to use one set of code for handling arrays, another set for handling objects. However, it's been not working properly for objects, and I'm curious if there'd be one way to write it that would work for both cases? If not what might be the best approach here?
My rough attempt to this point, if the code is helpful:
function reject(collection, callback) {
let newArr;
if (!collection.constructor == Array) {
newArr = {};
for (let [key, value] of Object.entries(collection)) {
if (!callback(value)) {
newArr[key] = value;
}
}
} else {
newArr = [];
for (let el of collection) {
if (!callback(el)){
newArr.push(el);
}
}
}
return newArr;
}
You can use Array.isArray to check if an object is an array. To remove elements from the array, you can iterate backwards and use Array#splice.
function reject(o, f) {
if (Array.isArray(o)) {
let res = [];
for (let i = o.length - 1; i >= 0; i--)
if (f(o[i])) res.push(o.splice(i, 1)[0]);
return res.reverse();
}
let res = {};
for (const [k, v] of Object.entries(o))
if (f(v)) {
res[k] = v;
delete o[k];
}
return res;
}
let a = [1, 2, 3, 4];
console.log(reject(a, x => x % 2 === 0), a);
let obj = {a : 1, b : 2, c : 3, d : 4};
console.log(reject(obj, x => x > 2), obj);

How filtered array if this array was exist on data selected? [duplicate]

Let A and B be two sets. I'm looking for really fast or elegant ways to compute the set difference (A - B or A \B, depending on your preference) between them. The two sets are stored and manipulated as Javascript arrays, as the title says.
Notes:
Gecko-specific tricks are okay
I'd prefer sticking to native functions (but I am open to a lightweight library if it's way faster)
I've seen, but not tested, JS.Set (see previous point)
Edit: I noticed a comment about sets containing duplicate elements. When I say "set" I'm referring to the mathematical definition, which means (among other things) that they do not contain duplicate elements.
I don't know if this is most effective, but perhaps the shortest:
var A = [1, 2, 3, 4];
var B = [1, 3, 4, 7];
var diff = A.filter(function(x) {
return B.indexOf(x) < 0;
});
console.log(diff); // [2]
Updated to ES6:
const A = [1, 2, 3, 4];
const B = [1, 3, 4, 7];
const diff = A.filter(x => !B.includes(x));
console.log(diff); // [2]
Well, 7 years later, with ES6's Set object it's quite easy (but still not as compact as python's A - B), and reportedly faster than indexOf for large arrays:
console.clear();
let a = new Set([1, 2, 3, 4]);
let b = new Set([5, 4, 3, 2]);
let a_minus_b = new Set([...a].filter(x => !b.has(x)));
let b_minus_a = new Set([...b].filter(x => !a.has(x)));
let a_intersect_b = new Set([...a].filter(x => b.has(x)));
let a_union_b = new Set([...a, ...b]);
console.log(...a_minus_b); // {1}
console.log(...b_minus_a); // {5}
console.log(...a_intersect_b); // {2,3,4}
console.log(...a_union_b); // {1,2,3,4,5}
Looking at a lof of these solutions, they do fine for small cases. But, when you blow them up to a million items, the time complexity starts getting silly.
A.filter(v => B.includes(v))
That starts looking like an O(N^2) solution. Since there is an O(N) solution, let's use it, you can easily modify to not be a generator if you're not up to date on your JS runtime.
function *setMinus(A, B) {
const setA = new Set(A);
const setB = new Set(B);
for (const v of setB.values()) {
if (!setA.delete(v)) {
yield v;
}
}
for (const v of setA.values()) {
yield v;
}
}
a = [1,2,3];
b = [2,3,4];
console.log(Array.from(setMinus(a, b)));
While this is a bit more complex than many of the other solutions, when you have large lists this will be far faster.
Let's take a quick look at the performance difference, running it on a set of 1,000,000 random integers between 0...10,000 we see the following performance results.
setMinus time = 181 ms
diff time = 19099 ms
function buildList(count, range) {
result = [];
for (i = 0; i < count; i++) {
result.push(Math.floor(Math.random() * range))
}
return result;
}
function *setMinus(A, B) {
const setA = new Set(A);
const setB = new Set(B);
for (const v of setB.values()) {
if (!setA.delete(v)) {
yield v;
}
}
for (const v of setA.values()) {
yield v;
}
}
function doDiff(A, B) {
return A.filter(function(x) { return B.indexOf(x) < 0 })
}
const listA = buildList(100_000, 100_000_000);
const listB = buildList(100_000, 100_000_000);
let t0 = process.hrtime.bigint()
const _x = Array.from(setMinus(listA, listB))
let t1 = process.hrtime.bigint()
const _y = doDiff(listA, listB)
let t2 = process.hrtime.bigint()
console.log("setMinus time = ", (t1 - t0) / 1_000_000n, "ms");
console.log("diff time = ", (t2 - t1) / 1_000_000n, "ms");
You can use an object as a map to avoid linearly scanning B for each element of A as in user187291's answer:
function setMinus(A, B) {
var map = {}, C = [];
for(var i = B.length; i--; )
map[B[i].toSource()] = null; // any other value would do
for(var i = A.length; i--; ) {
if(!map.hasOwnProperty(A[i].toSource()))
C.push(A[i]);
}
return C;
}
The non-standard toSource() method is used to get unique property names; if all elements already have unique string representations (as is the case with numbers), you can speed up the code by dropping the toSource() invocations.
If you're using Sets, it can be quite simple and performant:
function setDifference(a, b) {
return new Set(Array.from(a).filter(item => !b.has(item)));
}
Since Sets use Hash functions* under the hood, the has function is much faster than indexOf (this matters if you have, say, more than 100 items).
The shortest, using jQuery, is:
var A = [1, 2, 3, 4];
var B = [1, 3, 4, 7];
var diff = $(A).not(B);
console.log(diff.toArray());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
I would hash the array B, then keep values from the array A not present in B:
function getHash(array){
// Hash an array into a set of properties
//
// params:
// array - (array) (!nil) the array to hash
//
// return: (object)
// hash object with one property set to true for each value in the array
var hash = {};
for (var i=0; i<array.length; i++){
hash[ array[i] ] = true;
}
return hash;
}
function getDifference(a, b){
// compute the difference a\b
//
// params:
// a - (array) (!nil) first array as a set of values (no duplicates)
// b - (array) (!nil) second array as a set of values (no duplicates)
//
// return: (array)
// the set of values (no duplicates) in array a and not in b,
// listed in the same order as in array a.
var hash = getHash(b);
var diff = [];
for (var i=0; i<a.length; i++){
var value = a[i];
if ( !hash[value]){
diff.push(value);
}
}
return diff;
}
Using Underscore.js (Library for functional JS)
>>> var foo = [1,2,3]
>>> var bar = [1,2,4]
>>> _.difference(foo, bar);
[4]
Some simple functions, borrowing from #milan's answer:
const setDifference = (a, b) => new Set([...a].filter(x => !b.has(x)));
const setIntersection = (a, b) => new Set([...a].filter(x => b.has(x)));
const setUnion = (a, b) => new Set([...a, ...b]);
Usage:
const a = new Set([1, 2]);
const b = new Set([2, 3]);
setDifference(a, b); // Set { 1 }
setIntersection(a, b); // Set { 2 }
setUnion(a, b); // Set { 1, 2, 3 }
Incorporating the idea from Christoph and assuming a couple of non-standard iteration methods on arrays and objects/hashes (each and friends), we can get set difference, union and intersection in linear time in about 20 lines total:
var setOPs = {
minusAB : function (a, b) {
var h = {};
b.each(function (v) { h[v] = true; });
return a.filter(function (v) { return !h.hasOwnProperty(v); });
},
unionAB : function (a, b) {
var h = {}, f = function (v) { h[v] = true; };
a.each(f);
b.each(f);
return myUtils.keys(h);
},
intersectAB : function (a, b) {
var h = {};
a.each(function (v) { h[v] = 1; });
b.each(function (v) { h[v] = (h[v] || 0) + 1; });
var fnSel = function (v, count) { return count > 1; };
var fnVal = function (v, c) { return v; };
return myUtils.select(h, fnSel, fnVal);
}
};
This assumes that each and filter are defined for arrays, and that we have two utility methods:
myUtils.keys(hash): returns an
array with the keys of the hash
myUtils.select(hash, fnSelector,
fnEvaluator): returns an array with
the results of calling fnEvaluator
on the key/value pairs for which
fnSelector returns true.
The select() is loosely inspired by Common Lisp, and is merely filter() and map() rolled into one. (It would be better to have them defined on Object.prototype, but doing so wrecks havoc with jQuery, so I settled for static utility methods.)
Performance: Testing with
var a = [], b = [];
for (var i = 100000; i--; ) {
if (i % 2 !== 0) a.push(i);
if (i % 3 !== 0) b.push(i);
}
gives two sets with 50,000 and 66,666 elements. With these values A-B takes about 75ms, while union and intersection are about 150ms each. (Mac Safari 4.0, using Javascript Date for timing.)
I think that's decent payoff for 20 lines of code.
As for the fasted way, this isn't so elegant but I've run some tests to be sure. Loading one array as an object is far faster to process in large quantities:
var t, a, b, c, objA;
// Fill some arrays to compare
a = Array(30000).fill(0).map(function(v,i) {
return i.toFixed();
});
b = Array(20000).fill(0).map(function(v,i) {
return (i*2).toFixed();
});
// Simple indexOf inside filter
t = Date.now();
c = b.filter(function(v) { return a.indexOf(v) < 0; });
console.log('completed indexOf in %j ms with result %j length', Date.now() - t, c.length);
// Load `a` as Object `A` first to avoid indexOf in filter
t = Date.now();
objA = {};
a.forEach(function(v) { objA[v] = true; });
c = b.filter(function(v) { return !objA[v]; });
console.log('completed Object in %j ms with result %j length', Date.now() - t, c.length);
Results:
completed indexOf in 1219 ms with result 5000 length
completed Object in 8 ms with result 5000 length
However, this works with strings only. If you plan to compare numbered sets you'll want to map results with parseFloat.
The function below are ports of the methods found in Python's set() class and follows the TC39 Set methods proposal.
const
union = (a, b) => new Set([...a, ...b]),
intersection = (a, b) => new Set([...a].filter(x => b.has(x))),
difference = (a, b) => new Set([...a].filter(x => !b.has(x))),
symetricDifference = (a, b) => union(difference(a, b), difference(b, a)),
isSubsetOf = (a, b) => [...b].every(x => a.has(x)),
isSupersetOf = (a, b) => [...a].every(x => b.has(x)),
isDisjointFrom = (a, b) => !intersection(a, b).size;
const
a = new Set([1, 2, 3, 4]),
b = new Set([5, 4, 3, 2]);
console.log(...union(a, b)); // [1, 2, 3, 4, 5]
console.log(...intersection(a, b)); // [2, 3, 4]
console.log(...difference(a, b)); // [1]
console.log(...difference(b, a)); // [5]
console.log(...symetricDifference(a, b)); // [1, 5]
const
c = new Set(['A', 'B', 'C', 'D', 'E']),
d = new Set(['B', 'D']);
console.log(isSubsetOf(c, d)); // true
console.log(isSupersetOf(d, c)); // true
const
e = new Set(['A', 'B', 'C']),
f = new Set(['X', 'Y', 'Z']);
console.log(isDisjointFrom(e, f)); // true
.as-console-wrapper { top: 0; max-height: 100% !important; }
This works, but I think another one is much more shorter, and elegant too
A = [1, 'a', 'b', 12];
B = ['a', 3, 4, 'b'];
diff_set = {
ar : {},
diff : Array(),
remove_set : function(a) { ar = a; return this; },
remove: function (el) {
if(ar.indexOf(el)<0) this.diff.push(el);
}
}
A.forEach(diff_set.remove_set(B).remove,diff_set);
C = diff_set.diff;
Using core-js to polyfill the New Set methods proposal:
import "core-js"
new Set(A).difference(B)
In theory, the time complexity should be Θ(n), where n is the number of elements in B.

Javascript : Interchange X and Y value in nested list [duplicate]

Is there any simpler way to swap two elements in an array?
var a = list[x], b = list[y];
list[y] = a;
list[x] = b;
You only need one temporary variable.
var b = list[y];
list[y] = list[x];
list[x] = b;
Edit hijacking top answer 10 years later with a lot of ES6 adoption under our belts:
Given the array arr = [1,2,3,4], you can swap values in one line now like so:
[arr[0], arr[1]] = [arr[1], arr[0]];
This would produce the array [2,1,3,4]. This is destructuring assignment.
If you want a single expression, using native javascript,
remember that the return value from a splice operation
contains the element(s) that was removed.
var A = [1, 2, 3, 4, 5, 6, 7, 8, 9], x= 0, y= 1;
A[x] = A.splice(y, 1, A[x])[0];
alert(A); // alerts "2,1,3,4,5,6,7,8,9"
Edit:
The [0] is necessary at the end of the expression as Array.splice() returns an array, and in this situation we require the single element in the returned array.
According to some random person on Metafilter,
"Recent versions of Javascript allow you to do swaps (among other things) much more neatly:"
[ list[x], list[y] ] = [ list[y], list[x] ];
My quick tests showed that this Pythonic code works great in the version of JavaScript
currently used in "Google Apps Script" (".gs").
Alas, further tests show this code gives a "Uncaught ReferenceError: Invalid left-hand side in assignment." in
whatever version of JavaScript (".js") is used by
Google Chrome Version 24.0.1312.57 m.
This seems ok....
var b = list[y];
list[y] = list[x];
list[x] = b;
Howerver using
var b = list[y];
means a b variable is going to be to be present for the rest of the scope. This can potentially lead to a memory leak. Unlikely, but still better to avoid.
Maybe a good idea to put this into Array.prototype.swap
Array.prototype.swap = function (x,y) {
var b = this[x];
this[x] = this[y];
this[y] = b;
return this;
}
which can be called like:
list.swap( x, y )
This is a clean approach to both avoiding memory leaks and DRY.
Well, you don't need to buffer both values - only one:
var tmp = list[x];
list[x] = list[y];
list[y] = tmp;
You can swap elements in an array the following way:
list[x] = [list[y],list[y]=list[x]][0]
See the following example:
list = [1,2,3,4,5]
list[1] = [list[3],list[3]=list[1]][0]
//list is now [1,4,3,2,5]
Note: it works the same way for regular variables
var a=1,b=5;
a = [b,b=a][0]
This didn't exist when the question was asked, but ES2015 introduced array destructuring, allowing you to write it as follows:
let a = 1, b = 2;
// a: 1, b: 2
[a, b] = [b, a];
// a: 2, b: 1
Consider such a solution without a need to define the third variable:
function swap(arr, from, to) {
arr.splice(from, 1, arr.splice(to, 1, arr[from])[0]);
}
var letters = ["a", "b", "c", "d", "e", "f"];
swap(letters, 1, 4);
console.log(letters); // ["a", "e", "c", "d", "b", "f"]
Note: You may want to add additional checks for example for array length. This solution is mutable so swap function does not need to return a new array, it just does mutation over array passed into.
With numeric values you can avoid a temporary variable by using bitwise xor
list[x] = list[x] ^ list[y];
list[y] = list[y] ^ list[x];
list[x] = list[x] ^ list[y];
or an arithmetic sum (noting that this only works if x + y is less than the maximum value for the data type)
list[x] = list[x] + list[y];
list[y] = list[x] - list[y];
list[x] = list[x] - list[y];
To swap two consecutive elements of array
array.splice(IndexToSwap,2,array[IndexToSwap+1],array[IndexToSwap]);
For two or more elements (fixed number)
[list[y], list[x]] = [list[x], list[y]];
No temporary variable required!
I was thinking about simply calling list.reverse().
But then I realised it would work as swap only when list.length = x + y + 1.
For variable number of elements
I have looked into various modern Javascript constructions to this effect, including Map and map, but sadly none has resulted in a code that was more compact or faster than this old-fashioned, loop-based construction:
function multiswap(arr,i0,i1) {/* argument immutable if string */
if (arr.split) return multiswap(arr.split(""), i0, i1).join("");
var diff = [];
for (let i in i0) diff[i0[i]] = arr[i1[i]];
return Object.assign(arr,diff);
}
Example:
var alphabet = "abcdefghijklmnopqrstuvwxyz";
var [x,y,z] = [14,6,15];
var output = document.getElementsByTagName("code");
output[0].innerHTML = alphabet;
output[1].innerHTML = multiswap(alphabet, [0,25], [25,0]);
output[2].innerHTML = multiswap(alphabet, [0,25,z,1,y,x], [25,0,x,y,z,3]);
<table>
<tr><td>Input:</td> <td><code></code></td></tr>
<tr><td>Swap two elements:</td> <td><code></code></td></tr>
<tr><td>Swap multiple elements: </td> <td><code></code></td></tr>
</table>
what about Destructuring_assignment
var arr = [1, 2, 3, 4]
[arr[index1], arr[index2]] = [arr[index2], arr[index1]]
which can also be extended to
[src order elements] => [dest order elements]
Digest from http://www.greywyvern.com/?post=265
var a = 5, b = 9;
b = (a += b -= a) - b;
alert([a, b]); // alerts "9, 5"
You can swap any number of objects or literals, even of different types, using a simple identity function like this:
var swap = function (x){return x};
b = swap(a, a=b);
c = swap(a, a=b, b=c);
For your problem:
var swap = function (x){return x};
list[y] = swap(list[x], list[x]=list[y]);
This works in JavaScript because it accepts additional arguments even if they are not declared or used. The assignments a=b etc, happen after a is passed into the function.
There is one interesting way of swapping:
var a = 1;
var b = 2;
[a,b] = [b,a];
(ES6 way)
Here's a one-liner that doesn't mutate list:
let newList = Object.assign([], list, {[x]: list[y], [y]: list[x]})
(Uses language features not available in 2009 when the question was posted!)
var a = [1,2,3,4,5], b=a.length;
for (var i=0; i<b; i++) {
a.unshift(a.splice(1+i,1).shift());
}
a.shift();
//a = [5,4,3,2,1];
var arr = [1, 2];
arr.splice(0, 2, arr[1], arr[0]);
console.log(arr); //[2, 1]
Flow
not inplace solution
let swap= (arr,i,j)=> arr.map((e,k)=> k-i ? (k-j ? e : arr[i]) : arr[j]);
let swap= (arr,i,j)=> arr.map((e,k)=> k-i ? (k-j ? e : arr[i]) : arr[j]);
// test index: 3<->5 (= 'f'<->'d')
let a= ["a","b","c","d","e","f","g"];
let b= swap(a,3,5);
console.log(a,"\n", b);
console.log('Example Flow:', swap(a,3,5).reverse().join('-') );
and inplace solution
let swap= (arr,i,j)=> {let t=arr[i]; arr[i]=arr[j]; arr[j]=t; return arr}
// test index: 3<->5 (= 'f'<->'d')
let a= ["a","b","c","d","e","f","g"];
console.log( swap(a,3,5) )
console.log('Example Flow:', swap(a,3,5).reverse().join('-') );
In this solutions we use "flow pattern" which means that swap function returns array as result - this allow to easily continue processing using dot . (like reverse and join in snippets)
Here's a compact version
swaps value at i1 with i2 in arr
arr.slice(0,i1).concat(arr[i2],arr.slice(i1+1,i2),arr[i1],arr.slice(i2+1))
Here is a variation that first checks if the index exists in the array:
Array.prototype.swapItems = function(a, b){
if( !(a in this) || !(b in this) )
return this;
this[a] = this.splice(b, 1, this[a])[0];
return this;
}
It currently will just return this if the index does not exist, but you could easily modify behavior on fail
If you don't want to use temp variable in ES5, this is one way to swap array elements.
var swapArrayElements = function (a, x, y) {
if (a.length === 1) return a;
a.splice(y, 1, a.splice(x, 1, a[y])[0]);
return a;
};
swapArrayElements([1, 2, 3, 4, 5], 1, 3); //=> [ 1, 4, 3, 2, 5 ]
Array.prototype.swap = function(a, b) {
var temp = this[a];
this[a] = this[b];
this[b] = temp;
};
Usage:
var myArray = [0,1,2,3,4...];
myArray.swap(4,1);
Typescript solution that clones the array instead of mutating existing one
export function swapItemsInArray<T>(items: T[], indexA: number, indexB: number): T[] {
const itemA = items[indexA];
const clone = [...items];
clone[indexA] = clone[indexB];
clone[indexB] = itemA;
return clone;
}
If you are not allowed to use in-place swap for some reason, here is a solution with map:
function swapElements(array, source, dest) {
return source === dest
? array : array.map((item, index) => index === source
? array[dest] : index === dest
? array[source] : item);
}
const arr = ['a', 'b', 'c'];
const s1 = swapElements(arr, 0, 1);
console.log(s1[0] === 'b');
console.log(s1[1] === 'a');
const s2 = swapElements(arr, 2, 0);
console.log(s2[0] === 'c');
console.log(s2[2] === 'a');
Here is typescript code for quick copy-pasting:
function swapElements(array: Array<any>, source: number, dest: number) {
return source === dest
? array : array.map((item, index) => index === source
? array[dest] : index === dest
? array[source] : item);
}
For the sake of brevity, here's the ugly one-liner version that's only slightly less ugly than all that concat and slicing above. The accepted answer is truly the way to go and way more readable.
Given:
var foo = [ 0, 1, 2, 3, 4, 5, 6 ];
if you want to swap the values of two indices (a and b); then this would do it:
foo.splice( a, 1, foo.splice(b,1,foo[a])[0] );
For example, if you want to swap the 3 and 5, you could do it this way:
foo.splice( 3, 1, foo.splice(5,1,foo[3])[0] );
or
foo.splice( 5, 1, foo.splice(3,1,foo[5])[0] );
Both yield the same result:
console.log( foo );
// => [ 0, 1, 2, 5, 4, 3, 6 ]
#splicehatersarepunks:)
Swap the first and last element in an array without temporary variable or ES6 swap method [a, b] = [b, a]
[a.pop(), ...a.slice(1), a.shift()]
function moveElement(array, sourceIndex, destinationIndex) {
return array.map(a => a.id === sourceIndex ? array.find(a => a.id === destinationIndex): a.id === destinationIndex ? array.find(a => a.id === sourceIndex) : a )
}
let arr = [
{id: "1",title: "abc1"},
{id: "2",title: "abc2"},
{id: "3",title: "abc3"},
{id: "4",title: "abc4"}];
moveElement(arr, "2","4");
in place swap
// array methods
function swapInArray(arr, i1, i2){
let t = arr[i1];
arr[i1] = arr[i2];
arr[i2] = t;
}
function moveBefore(arr, el){
let ind = arr.indexOf(el);
if(ind !== -1 && ind !== 0){
swapInArray(arr, ind, ind - 1);
}
}
function moveAfter(arr, el){
let ind = arr.indexOf(el);
if(ind !== -1 && ind !== arr.length - 1){
swapInArray(arr, ind + 1, ind);
}
}
// dom methods
function swapInDom(parentNode, i1, i2){
parentNode.insertBefore(parentNode.children[i1], parentNode.children[i2]);
}
function getDomIndex(el){
for (let ii = 0; ii < el.parentNode.children.length; ii++){
if(el.parentNode.children[ii] === el){
return ii;
}
}
}
function moveForward(el){
let ind = getDomIndex(el);
if(ind !== -1 && ind !== 0){
swapInDom(el.parentNode, ind, ind - 1);
}
}
function moveBackward(el){
let ind = getDomIndex(el);
if(ind !== -1 && ind !== el.parentNode.children.length - 1){
swapInDom(el.parentNode, ind + 1, ind);
}
}
Just for the fun of it, another way without using any extra variable would be:
var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9];
// swap index 0 and 2
arr[arr.length] = arr[0]; // copy idx1 to the end of the array
arr[0] = arr[2]; // copy idx2 to idx1
arr[2] = arr[arr.length-1]; // copy idx1 to idx2
arr.length--; // remove idx1 (was added to the end of the array)
console.log( arr ); // -> [3, 2, 1, 4, 5, 6, 7, 8, 9]

Swap json values [duplicate]

Is there any simpler way to swap two elements in an array?
var a = list[x], b = list[y];
list[y] = a;
list[x] = b;
You only need one temporary variable.
var b = list[y];
list[y] = list[x];
list[x] = b;
Edit hijacking top answer 10 years later with a lot of ES6 adoption under our belts:
Given the array arr = [1,2,3,4], you can swap values in one line now like so:
[arr[0], arr[1]] = [arr[1], arr[0]];
This would produce the array [2,1,3,4]. This is destructuring assignment.
If you want a single expression, using native javascript,
remember that the return value from a splice operation
contains the element(s) that was removed.
var A = [1, 2, 3, 4, 5, 6, 7, 8, 9], x= 0, y= 1;
A[x] = A.splice(y, 1, A[x])[0];
alert(A); // alerts "2,1,3,4,5,6,7,8,9"
Edit:
The [0] is necessary at the end of the expression as Array.splice() returns an array, and in this situation we require the single element in the returned array.
According to some random person on Metafilter,
"Recent versions of Javascript allow you to do swaps (among other things) much more neatly:"
[ list[x], list[y] ] = [ list[y], list[x] ];
My quick tests showed that this Pythonic code works great in the version of JavaScript
currently used in "Google Apps Script" (".gs").
Alas, further tests show this code gives a "Uncaught ReferenceError: Invalid left-hand side in assignment." in
whatever version of JavaScript (".js") is used by
Google Chrome Version 24.0.1312.57 m.
This seems ok....
var b = list[y];
list[y] = list[x];
list[x] = b;
Howerver using
var b = list[y];
means a b variable is going to be to be present for the rest of the scope. This can potentially lead to a memory leak. Unlikely, but still better to avoid.
Maybe a good idea to put this into Array.prototype.swap
Array.prototype.swap = function (x,y) {
var b = this[x];
this[x] = this[y];
this[y] = b;
return this;
}
which can be called like:
list.swap( x, y )
This is a clean approach to both avoiding memory leaks and DRY.
Well, you don't need to buffer both values - only one:
var tmp = list[x];
list[x] = list[y];
list[y] = tmp;
You can swap elements in an array the following way:
list[x] = [list[y],list[y]=list[x]][0]
See the following example:
list = [1,2,3,4,5]
list[1] = [list[3],list[3]=list[1]][0]
//list is now [1,4,3,2,5]
Note: it works the same way for regular variables
var a=1,b=5;
a = [b,b=a][0]
This didn't exist when the question was asked, but ES2015 introduced array destructuring, allowing you to write it as follows:
let a = 1, b = 2;
// a: 1, b: 2
[a, b] = [b, a];
// a: 2, b: 1
Consider such a solution without a need to define the third variable:
function swap(arr, from, to) {
arr.splice(from, 1, arr.splice(to, 1, arr[from])[0]);
}
var letters = ["a", "b", "c", "d", "e", "f"];
swap(letters, 1, 4);
console.log(letters); // ["a", "e", "c", "d", "b", "f"]
Note: You may want to add additional checks for example for array length. This solution is mutable so swap function does not need to return a new array, it just does mutation over array passed into.
With numeric values you can avoid a temporary variable by using bitwise xor
list[x] = list[x] ^ list[y];
list[y] = list[y] ^ list[x];
list[x] = list[x] ^ list[y];
or an arithmetic sum (noting that this only works if x + y is less than the maximum value for the data type)
list[x] = list[x] + list[y];
list[y] = list[x] - list[y];
list[x] = list[x] - list[y];
To swap two consecutive elements of array
array.splice(IndexToSwap,2,array[IndexToSwap+1],array[IndexToSwap]);
For two or more elements (fixed number)
[list[y], list[x]] = [list[x], list[y]];
No temporary variable required!
I was thinking about simply calling list.reverse().
But then I realised it would work as swap only when list.length = x + y + 1.
For variable number of elements
I have looked into various modern Javascript constructions to this effect, including Map and map, but sadly none has resulted in a code that was more compact or faster than this old-fashioned, loop-based construction:
function multiswap(arr,i0,i1) {/* argument immutable if string */
if (arr.split) return multiswap(arr.split(""), i0, i1).join("");
var diff = [];
for (let i in i0) diff[i0[i]] = arr[i1[i]];
return Object.assign(arr,diff);
}
Example:
var alphabet = "abcdefghijklmnopqrstuvwxyz";
var [x,y,z] = [14,6,15];
var output = document.getElementsByTagName("code");
output[0].innerHTML = alphabet;
output[1].innerHTML = multiswap(alphabet, [0,25], [25,0]);
output[2].innerHTML = multiswap(alphabet, [0,25,z,1,y,x], [25,0,x,y,z,3]);
<table>
<tr><td>Input:</td> <td><code></code></td></tr>
<tr><td>Swap two elements:</td> <td><code></code></td></tr>
<tr><td>Swap multiple elements: </td> <td><code></code></td></tr>
</table>
what about Destructuring_assignment
var arr = [1, 2, 3, 4]
[arr[index1], arr[index2]] = [arr[index2], arr[index1]]
which can also be extended to
[src order elements] => [dest order elements]
Digest from http://www.greywyvern.com/?post=265
var a = 5, b = 9;
b = (a += b -= a) - b;
alert([a, b]); // alerts "9, 5"
You can swap any number of objects or literals, even of different types, using a simple identity function like this:
var swap = function (x){return x};
b = swap(a, a=b);
c = swap(a, a=b, b=c);
For your problem:
var swap = function (x){return x};
list[y] = swap(list[x], list[x]=list[y]);
This works in JavaScript because it accepts additional arguments even if they are not declared or used. The assignments a=b etc, happen after a is passed into the function.
There is one interesting way of swapping:
var a = 1;
var b = 2;
[a,b] = [b,a];
(ES6 way)
Here's a one-liner that doesn't mutate list:
let newList = Object.assign([], list, {[x]: list[y], [y]: list[x]})
(Uses language features not available in 2009 when the question was posted!)
var a = [1,2,3,4,5], b=a.length;
for (var i=0; i<b; i++) {
a.unshift(a.splice(1+i,1).shift());
}
a.shift();
//a = [5,4,3,2,1];
var arr = [1, 2];
arr.splice(0, 2, arr[1], arr[0]);
console.log(arr); //[2, 1]
Flow
not inplace solution
let swap= (arr,i,j)=> arr.map((e,k)=> k-i ? (k-j ? e : arr[i]) : arr[j]);
let swap= (arr,i,j)=> arr.map((e,k)=> k-i ? (k-j ? e : arr[i]) : arr[j]);
// test index: 3<->5 (= 'f'<->'d')
let a= ["a","b","c","d","e","f","g"];
let b= swap(a,3,5);
console.log(a,"\n", b);
console.log('Example Flow:', swap(a,3,5).reverse().join('-') );
and inplace solution
let swap= (arr,i,j)=> {let t=arr[i]; arr[i]=arr[j]; arr[j]=t; return arr}
// test index: 3<->5 (= 'f'<->'d')
let a= ["a","b","c","d","e","f","g"];
console.log( swap(a,3,5) )
console.log('Example Flow:', swap(a,3,5).reverse().join('-') );
In this solutions we use "flow pattern" which means that swap function returns array as result - this allow to easily continue processing using dot . (like reverse and join in snippets)
Here's a compact version
swaps value at i1 with i2 in arr
arr.slice(0,i1).concat(arr[i2],arr.slice(i1+1,i2),arr[i1],arr.slice(i2+1))
Here is a variation that first checks if the index exists in the array:
Array.prototype.swapItems = function(a, b){
if( !(a in this) || !(b in this) )
return this;
this[a] = this.splice(b, 1, this[a])[0];
return this;
}
It currently will just return this if the index does not exist, but you could easily modify behavior on fail
If you don't want to use temp variable in ES5, this is one way to swap array elements.
var swapArrayElements = function (a, x, y) {
if (a.length === 1) return a;
a.splice(y, 1, a.splice(x, 1, a[y])[0]);
return a;
};
swapArrayElements([1, 2, 3, 4, 5], 1, 3); //=> [ 1, 4, 3, 2, 5 ]
Array.prototype.swap = function(a, b) {
var temp = this[a];
this[a] = this[b];
this[b] = temp;
};
Usage:
var myArray = [0,1,2,3,4...];
myArray.swap(4,1);
Typescript solution that clones the array instead of mutating existing one
export function swapItemsInArray<T>(items: T[], indexA: number, indexB: number): T[] {
const itemA = items[indexA];
const clone = [...items];
clone[indexA] = clone[indexB];
clone[indexB] = itemA;
return clone;
}
If you are not allowed to use in-place swap for some reason, here is a solution with map:
function swapElements(array, source, dest) {
return source === dest
? array : array.map((item, index) => index === source
? array[dest] : index === dest
? array[source] : item);
}
const arr = ['a', 'b', 'c'];
const s1 = swapElements(arr, 0, 1);
console.log(s1[0] === 'b');
console.log(s1[1] === 'a');
const s2 = swapElements(arr, 2, 0);
console.log(s2[0] === 'c');
console.log(s2[2] === 'a');
Here is typescript code for quick copy-pasting:
function swapElements(array: Array<any>, source: number, dest: number) {
return source === dest
? array : array.map((item, index) => index === source
? array[dest] : index === dest
? array[source] : item);
}
For the sake of brevity, here's the ugly one-liner version that's only slightly less ugly than all that concat and slicing above. The accepted answer is truly the way to go and way more readable.
Given:
var foo = [ 0, 1, 2, 3, 4, 5, 6 ];
if you want to swap the values of two indices (a and b); then this would do it:
foo.splice( a, 1, foo.splice(b,1,foo[a])[0] );
For example, if you want to swap the 3 and 5, you could do it this way:
foo.splice( 3, 1, foo.splice(5,1,foo[3])[0] );
or
foo.splice( 5, 1, foo.splice(3,1,foo[5])[0] );
Both yield the same result:
console.log( foo );
// => [ 0, 1, 2, 5, 4, 3, 6 ]
#splicehatersarepunks:)
Swap the first and last element in an array without temporary variable or ES6 swap method [a, b] = [b, a]
[a.pop(), ...a.slice(1), a.shift()]
function moveElement(array, sourceIndex, destinationIndex) {
return array.map(a => a.id === sourceIndex ? array.find(a => a.id === destinationIndex): a.id === destinationIndex ? array.find(a => a.id === sourceIndex) : a )
}
let arr = [
{id: "1",title: "abc1"},
{id: "2",title: "abc2"},
{id: "3",title: "abc3"},
{id: "4",title: "abc4"}];
moveElement(arr, "2","4");
in place swap
// array methods
function swapInArray(arr, i1, i2){
let t = arr[i1];
arr[i1] = arr[i2];
arr[i2] = t;
}
function moveBefore(arr, el){
let ind = arr.indexOf(el);
if(ind !== -1 && ind !== 0){
swapInArray(arr, ind, ind - 1);
}
}
function moveAfter(arr, el){
let ind = arr.indexOf(el);
if(ind !== -1 && ind !== arr.length - 1){
swapInArray(arr, ind + 1, ind);
}
}
// dom methods
function swapInDom(parentNode, i1, i2){
parentNode.insertBefore(parentNode.children[i1], parentNode.children[i2]);
}
function getDomIndex(el){
for (let ii = 0; ii < el.parentNode.children.length; ii++){
if(el.parentNode.children[ii] === el){
return ii;
}
}
}
function moveForward(el){
let ind = getDomIndex(el);
if(ind !== -1 && ind !== 0){
swapInDom(el.parentNode, ind, ind - 1);
}
}
function moveBackward(el){
let ind = getDomIndex(el);
if(ind !== -1 && ind !== el.parentNode.children.length - 1){
swapInDom(el.parentNode, ind + 1, ind);
}
}
Just for the fun of it, another way without using any extra variable would be:
var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9];
// swap index 0 and 2
arr[arr.length] = arr[0]; // copy idx1 to the end of the array
arr[0] = arr[2]; // copy idx2 to idx1
arr[2] = arr[arr.length-1]; // copy idx1 to idx2
arr.length--; // remove idx1 (was added to the end of the array)
console.log( arr ); // -> [3, 2, 1, 4, 5, 6, 7, 8, 9]

Is there a shortcut to create padded array in JavaScript?

I have this javascript:
function padded_array(k, value){
var a = [];
a[k] = value;
return a;
}
padded_array(3, "hello"); //=> [undefined, undefined, undefined, 'hello']
Is it possible to shorten the code in the function body?
for all the googlers coming here - you're probably looking for this:
var pad_array = function(arr,len,fill) {
return arr.concat(Array(len).fill(fill)).slice(0,len);
}
From 2020 & 2021 : straight forward options
Let assume that is your Array
const yourArray = [1,2]
If you just want to loop 4 times (maybe for react jsx )
Array.from({length:4}) //[undefined,undefined,undefined,undefined]
Array(4).fill()//[undefined,undefined,undefined,undefined]
If you want to loop yourArray 4 times, but to start with values you already have
// unmutation option
Array.from({...yourArray, length:4}) //[1,2,undefined,undefined]
// unmutation option, but need some calcualtion
[...yourArray , ...Array(2) ] //[1,2,undefined,undefined]
[...Array(2), ...yourArray ] //[undefined,undefined,1,2]
// loop on your array several times
Array(3).fill(yourArray).flat() // [1, 2, 1, 2, 1, 2]
// mutation the original array.
yourArray.length = 4;
Array.from(yourArray) //[1,2,undefined,undefined]
If You actually want an Array with full of values. ex. with increment numbers.
Remap it
// unmutation option
Array.from({...yourArray,length:4}, (v,i) => v ?? i+1 )
// [1,'2',3, 4]
// Or, mutation the original array. and fill with "x"
array.yourArray.length = 4;
Array.from(yourArray, (v) => v ?? 'x')
// [1,'2','x','x']
If you want to exclude the 'hello', you can use
new Array(count);
to create padded Arrays.
Edit: Maybe like this ?
new Array(5).concat("hello")
Another solution using spread operator:
padArray = (length, value) => [...Array(length).fill(), value];
And the usage is the same as you mentioned:
padded_array(3, "hello"); //=> [undefined, undefined, undefined, 'hello']
For padding at the start:
function padArrayStart(arr, len, padding){
return Array(len - arr.length).fill(padding).concat(arr);
}
Demo:
function padArrayStart(arr, len, padding){
return Array(len - arr.length).fill(padding).concat(arr);
}
console.log(...padArrayStart([1,2,3], 5, 0));//0 0 1 2 3
console.log(...padArrayStart([4,5,6], 3, 0));//4 5 6
For padding at the end:
function padArrayEnd(arr, len, padding){
return arr.concat(Array(len - arr.length).fill(padding));
}
Demo:
function padArrayEnd(arr, len, padding){
return arr.concat(Array(len - arr.length).fill(padding));
}
console.log(...padArrayEnd(['a','b','c'], 10, 'z'));//a b c z z z z z z z
console.log(...padArrayEnd([0, 'a', 'd'], 6, -1));//0 a d -1 -1 -1
Not in standard ES5 or predecessor. Surely you can do something like $.extend([], {"3": "hello"}) in jQuery; you can even do
Object.create(Array.prototype, {"3": {value: "hello"} });
in bare ES5, but it is hack, I would not consider this a solution (if it is ok with you, you can adopt it).
You can use that if your JS doesn't support Array.prototype.fill() (ex. Google Apps Script) and you can't use the code from the first answer:
function array_pad(array, length, filler)
{
if(array.length < length)// [10.02.20] Fixed error that Dimitry K noticed
while(true)
if(array.push(filler) >= length)
break;
return array;
}
I know this is an old(er) question but wanted to add my 2 cents if someone stumbles here (like i initially did).
Anyway, heres my take with Array.from
const padded_array = (k, value) => Array.from({ length: k }).concat(value)
console.log(padded_array(3, "hello"));
Also you could do it with something like this:
const padded = (arr, pad, val) => {
arr[pad] = val
return arr
}
console.log(padded([],3,'hello'))
// push is faster than concat
// mutate array in place + return array
const pad_right = (a, l, f) =>
!Array.from({length: l - a.length})
.map(_ => a.push(f)) || a;
const a = [1, 2];
pad_right(a, 4, 'x');
// -> [ 1, 2, 'x', 'x' ]
a;
// -> [ 1, 2, 'x', 'x' ]
function leftPad(array, desiredLength, padding) {
array.unshift(...Array(desiredLength - array.length).fill(padding));
}
function rightPad(array, desiredLength, padding) {
array.push(...Array(desiredLength - array.length).fill(padding));
}
const myHello = ['hello'];
leftPad(myHello, 3, undefined);
// [undefined, undefined, 'hello']
const myHello2 = ['hello2'];
rightPad(myHello, 3, 0);
// ['hello2', 0, 0];

Categories

Resources