1

Let's say that I have an array var x = [1, 2, 3, 4], and I would like to add 1 to the second and the third element of the array. In Python numpy I could do x[1:3] += 1 to add to the interval from 1st to 3rd (3rd excluded) element of x. Is there a similar method in JavaScript?

5
  • So 1 would be the second and 3 the third element? Commented Apr 16, 2021 at 16:24
  • 1
    there is no such method is JavaScript. You can try mapping over the array if you want to avoid traditional for loop Commented Apr 16, 2021 at 16:24
  • No. You need to use a for loop. Commented Apr 16, 2021 at 16:24
  • You can try this x = x.map((v, i) => (i >= 1 && i < 3 ? v + 1 : v)); Commented Apr 16, 2021 at 16:24
  • [2, 3].forEach((v) => (x[v - 1] += 1)); where [2,3] are second and third element from given array. Commented Apr 16, 2021 at 16:37

2 Answers 2

2

You could take a function with a closure

const
    map = (start, end, fn) => (v, i) => i >= start && i <= end ? fn(v) : v,
    x = [1, 2, 3, 4],
    result = x.map(map(1, 2, v => v + 1));

console.log(result);

Sign up to request clarification or add additional context in comments.

Comments

0

It's hard to beat python on this, but how about golang? Here's a quick POC:

function _toInt(s, def = null) {
    try {
        let n = Number(s);
        return Number.isInteger(n) ? n : def;
    } catch {
        return def;
    }
}

class _Slice {
    constructor(ary, idx) {
        this.ary = ary;
        let ii = idx.split(':');
        this.start = _toInt(ii[0], 0);
        this.end = _toInt(ii[1], ary.length);
        this.step = _toInt(ii[2], 1);
    }

    get(obj, p) {
        let n = _toInt(p);
        if (n === null)
            return this[p];
        let k = this.start + n * this.step;
        return this.ary[k];
    }

    set(obj, p, val) {
        let n = _toInt(p);
        if (n === null)
            return this[p] = val;
        let k = this.start + n * this.step;
        return this.ary[k] = val;
    }

    * [Symbol.iterator]() {
        for (let i = 0, k = this.start; k < this.end; k += this.step, i++) {
            yield [i, this.ary[k]]
        }
    }
}

let Slice = (ary, idx) => new Proxy([], new _Slice(ary, idx));

//

let array = [0, 11, 22, 33, 44, 55, 66, 77, 88, 99]

let slice = Slice(array, '1:8:2')

for (let [i, _] of slice)
    slice[i] *= 100;

console.log(array)

With some more love, this should allow us to do

Slice([1,2,3,4,5,6])['1::4'] = 9 // [1,9,9,9,5,6] 
Slice([1,2,3,4,5,6])['1::4'] = [7, 8, 9] // [1,7,8,9,5,6]

and of course

Slice([1,2,3,4,5,6])['::-1'] // [6,5,4,3,2,1]

2 Comments

... what is love ...?
@NinaScholz: indeed ))))

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.