I wanted make [1,2,3,4,5].duplicated()
works but when I wrote:
Array.prototype.duplicator = function (){
var a = [];
for(var i=0;i<10;i+=2){
a[i]=this[i];
a[i+1]=this[i];
}
return a;
};
[1,2,3,4,5].duplicator();
it returns [1, 1, 3, 3, 5, 5, undefined, undefined, undefined, undefined]
instead of [1,1,2,2,3,3,4,4,5,5]
. Can anyone tell me why it does not work?
I wanted make [1,2,3,4,5].duplicated()
works but when I wrote:
Array.prototype.duplicator = function (){
var a = [];
for(var i=0;i<10;i+=2){
a[i]=this[i];
a[i+1]=this[i];
}
return a;
};
[1,2,3,4,5].duplicator();
it returns [1, 1, 3, 3, 5, 5, undefined, undefined, undefined, undefined]
instead of [1,1,2,2,3,3,4,4,5,5]
. Can anyone tell me why it does not work?
9 Answers
Reset to default 5Array.prototype.duplicator=function()
{
return this.concat(this)
}
alert([1,2,3,4,5].duplicator());
You could just map
and flatten for a more functional approach:
Array.prototype.duplicate = function() {
return [].concat.apply([], this.map(function(v) {
return [v,v];
}));
};
console.log([1,2,3].duplicate()); //=> [1,1,2,2,3,3]
The simplest answer should be:
Array.prototype.duplicator=function () {
return this.concat(this).sort();
}
console.log([1,2,3,4,5].duplicator());//[1,1,2,2,3,3,4,4,5,5]
Because you're adding 2 at each iteration, thus stepping beyond the array boundaries. Try this instead:
for (var i=0; i<this.length; i++) {
a.push(this[i]);
a.push(this[i]);
}
You would want to place each value in i*2
and i*2+1
instead of i
and i+1
, and loop one step at a time:
Array.prototype.duplicator = function (){
var a = [];
for(var i = 0; i < this.length; i++){
a[i*2] = this[i];
a[i*2+1] = this[i];
}
return a;
};
Here's a fix:
Array.prototype.duplicator = function() {
var dup = [];
for (var i = 0; i < this.length; i++) {
dup[2 * i] = dup[2 * i + 1] = this[i];
}
return dup;
};
console.log([1,2,3,4,5].duplicator());
Array.prototype.duplicator = function () {
var a = [], k = 0;
for(var i=0;i<this.length;i++) {
a[k]=this[i];
k++;
a[k]=this[i];
k++;
}
return a;
};
duplicator = val => val.concat(val);
This works for me following the case in https://github./h5bp/Front-end-Developer-Interview-Questions/blob/master/src/questions/javascript-questions.md, where the desired result is [1, 2, 3, 4, 5, 1, 2, 3, 4, 5]. Hope it works for you!
const duplicate = (...nums) => [].concat(...nums, ...nums);
console.log(duplicate([1, 2, 3, 4, 5]));