Reputation: 27
So I was given the problem to write a function that will take a given array, add a given number to it and output a new array adding the given number to each element in the array.. so given_array = [1, 2, 3, 4, 5] ... function add(5) .... new_array (or maybe change the old array) = [6, 7, 8, 9, 10] .
Here is the question:
// write code so that console logs print out true
// add(addValue) should return a new arrays where addValue
// is added to each value of original array
// i.e. [6, 7, 8, 9, 10] >
var e = [1, 2, 3, 4, 5];
console.log(e.add(5) == '[6,7,8,9,10]');
this gives me my result but this is not the question
var e = [1, 2, 3, 4, 5];
var addValue = (e, Val) => e.map(add=>add+Val);
console.log(addValue(e,5));
Upvotes: 0
Views: 90
Reputation: 51926
The most straightforward way to do this would be to invoke Array#map()
with a scoped function from within Array#add()
, using the number
argument passed in:
Array.prototype.add = function add (number) {
return JSON.stringify(this.map(value => value + number))
}
var e = [1, 2, 3, 4, 5]
console.log(e.add(5) == '[6,7,8,9,10]')
The reason you must wrap in JSON.stringify()
is because Array#toString()
and Array#join()
do not include the wrapping square brackets as in JSON encoding.
Upvotes: 1
Reputation: 1483
Use prototypes
Array.prototype.add = function(val) {
for(var i=0;i<this.length;i++){
this[i] = this[i]+val;
}
};
e.add(6);
console.log(e);
Upvotes: 0
Reputation: 63550
Write a function that accepts the integer that you're going to add with, and returns a new function that will perform the addition calculation when you pass it an array:
function add(n) {
return function (arr) {
return arr.map(function (el) {
return n + el;
});
}
}
const add5 = add(5);
add5([1, 2, 3, 4, 5]); // [6, 7, 8, 9, 10]
You don't even need to create a new variable to hold the returned function:
add(5)([1, 2, 3, 4, 5]);
In an ES6 one-liner:
const add = (n) => (arr) => arr.map(el => n + el);
And if you really wanted to add it to the Array.prototype
(making sure you check that the new method you're proposing isn't already on the the prototype):
if (!(Array.prototype.add)) {
Array.prototype.add = function (n) {
return this.map(function (el) {
return n + el;
});
}
}
[1, 2, 3, 4, 5].add(5); // [6, 7, 8, 9, 10]
Upvotes: 2