最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Write a function that doubles up each item in an array - Stack Overflow

programmeradmin2浏览0评论

This is in javascript. So far, I've got this:

 var double = function (array) {
     var array = [];
     for(var i = 0; i<array.length; i++) {
         var sum = array[i] + array[i];
     }
     return sum;
};

...Basically, if I entered in this area:

var a = [1,2,3];

I would want the function to return:

[1,1,2,2,3,3]

...etc

This is in javascript. So far, I've got this:

 var double = function (array) {
     var array = [];
     for(var i = 0; i<array.length; i++) {
         var sum = array[i] + array[i];
     }
     return sum;
};

...Basically, if I entered in this area:

var a = [1,2,3];

I would want the function to return:

[1,1,2,2,3,3]

...etc

Share Improve this question edited Dec 11, 2014 at 6:38 Chris Martin 30.7k12 gold badges80 silver badges140 bronze badges asked Dec 11, 2014 at 6:35 user4348721user4348721 311 gold badge1 silver badge4 bronze badges 4
  • use double as variable name? It's a reserved word in ECMAScript standard 1 ~ 3. See this – Raptor Commented Dec 11, 2014 at 6:37
  • 1 You are just summing some elements of the array... You need to (1) iterate through the array (2) insert the encountered element twice in another array (3à) return the newly constructed array. The parameter array is the one to iterate through, and you must construct a local one with a different name, say myDoublingArray, write the code is suggested you and return myDoublingArray. – Jean-Baptiste Yunès Commented Dec 11, 2014 at 6:40
  • 1 stackoverflow.com/questions/12503146/… – Paul Commented Dec 11, 2014 at 6:41
  • @Raptor: You mean it was a reserved keyword until edition 3? Don't bother any more. – Bergi Commented Dec 11, 2014 at 6:48
Add a comment  | 

8 Answers 8

Reset to default 8

Way with reduce, maybe the shortest one

[1,2,3].reduce(function(m,i) { return m.concat([i,i]); }, []);

and ES6 version

[1,2,3].reduce((m,i) => m.concat([i,i]), []);

Here's a concise way to do this:

function doubleValues(array) {
   return array.concat.apply([], array.map(function (el) { return [el, el] }));
}

console.log(doubleValues([1, 2, 3]));

A somewhat more easy-to-understand approach:

function doubleValues(array) {
  var newArray = [];
  array.forEach(function (el) { newArray.push(el, el); });    
  return newArray;
}

console.log(doubleValues([1,2,3]));

And an ESNext version:

const doubleValues = array => array.flatMap(el => [el,el]);

console.log(doubleValues([1, 2, 3]));

Untested code, I'm not overly familiar with javascript, so this might have some syntactical errors:

var duplicateArrayMembers = function (array) {
  var result = [];
  for (var i = 0; i < array.length; ++i) {
    result.push(array[i]);
    result.push(array[i]);
  }
  return result;
}

var myArray = [1, 2, 3];
document.write(duplicateArrayMembers(myArray));

First, we declare a function with a parameter named array. Because array is a parameter, we don't need to declare it in the function body.

Next, we declare the array where we will put the result of our duplication. Let's name this simply result.

Next, we loop through the array. And for every member of the array we push the element to the end of the result. Which means if the first member is 1 we push 1 two different times ending up with [1,1] after the first step.

Finally, after we have looped through the array, we return our result.

Here's more concise way do to it.

function doubleArr(arr){
   var rtn = []; 
   return arr.forEach(function(x){ rtn.push(x, x); }), rtn;
}

Calling it

console.log(doubleArr([1,2,3])); // [1, 1, 2, 2, 3, 3]

Here's a simple one-liner if only array of Numbers is concerned.

function doubleArr(arr){
   return arr.map(function(x){ return [x,x]}).join().split(",").map(Number);
}

Try this:

var dob = function (array) {
    var test = [];
   for(var i = 0; i<array.length; i++) {
       var sum = array[i];
       test.push(sum);test.push(sum);
  }
   console.log(test);
  };

dob([1,2,3])

FIDDLE

I changed your function a little bit.

The idea is to .push(item) into another array TWICE.

function double(array) {
  var output = [];
  for(var i = 0; i < array.length; i++) {
    output.push(array[i]);
    output.push(array[i]);
  }
  return output;
};

var input = [1,2,3];

var output = double(input);

alert(output);

Apart from all the ways of doing it with pure Javascript that you can find in other answers, you could use a library like underscore or lo-dash, or similar, in which case you could write it as:

_.chain(array).map(function(x) {return [x,x]}).flatten().value()

The chain function will wrap your array in an object, so you can apply successive functions on it. If you start with [1, 2, 3] then map will return [[1,1],[2,2],[3,3]]. After that flatten will flatten your array to [1,1,2,2,3,3], and value() just unwraps it from the object so you can use it.

This one worked for me:

Given an array of integers, return a new array with each value doubled.

For example:

[1, 2, 3] --> [2, 4, 6]

For the beginner, try to use the map method - it comes in very handy quite a lot so is a good one to know.

function maps(integers) {
return integers.concat.apply([],
integers.map(function (n) { 
return [n*2] }));
};
发布评论

评论列表(0)

  1. 暂无评论