Gaterde
Gaterde

Reputation: 819

Create JS array with dynamic values

Currently I create an array like this:

[c%256,2*c%256,3*c%256,4*c%256]

I have to multiply the variable c with the current position in array + 1 and then modulo 256.

Is there a better / smaller way to do that. Something with ES6?

Say I want that with an array length of 20?

Upvotes: 0

Views: 384

Answers (6)

OliverRadini
OliverRadini

Reputation: 6467

Is this what you need?

const c = 32;

const result = Array(20).fill().map((x,i) => (c * i+1) % 256);

console.dir(result);

Upvotes: 0

Steven Spungin
Steven Spungin

Reputation: 29109

This uses ES6 map. It avoids a loop or array declaration. The array is allocated with the correct size from the start (no pushing/resizing).

//[c%256,2*c%256,3*c%256,4*c%256]

const c = 12
const count = 100

const items = Array(count).fill().map((_, i) => ((i + 1) * c) % 256)

console.log(items)

Upvotes: 1

Federico Roma
Federico Roma

Reputation: 126

const createArray = (length, c) => {
  return [...Array(length).keys()].map(i => (i + 1) * c % 256)
}

Upvotes: 3

Beginner
Beginner

Reputation: 9105

var c = 5;
var arr = Array.apply(null, Array(20))
var output = arr.map( (v,i) => (c*(i+1)%256) )
console.log(output)

// single line
var c = 8
console.log(Array.apply(null, Array(20)).map( (v,i) => (c*(i+1)%256) ))

Upvotes: 0

JanS
JanS

Reputation: 2075

You can do this without ES6:

function createArray(variable, length) {
    var arr = [];

    for(var i = 0; i < length; i++) {
        arr.push((i+1) * variable % 256);
    }

    return arr;
}

Upvotes: -2

Nina Scholz
Nina Scholz

Reputation: 386604

You could use Array.from and generate an array with the wanted length and map the wanted values.

function getArray(length, c) {
    var f = c % 256;
    return Array.from({ length }, (_, i) => f * (i + 1));
}

console.log(getArray(5, 266));

Upvotes: 3

Related Questions