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?
2 Answers
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
Nina Scholz
... what is love ...?
georg
@NinaScholz: indeed ))))
1would be the second and3the third element?forloop.x = x.map((v, i) => (i >= 1 && i < 3 ? v + 1 : v));[2, 3].forEach((v) => (x[v - 1] += 1));where [2,3] are second and third element from given array.