Replacing multiple elements of an array while keeping their position
You can use an object to associate each character to a specific integer: obj
:
const obj = {a:1, b:2, c:3, d:4, e:5, f:6};
Then use the .map
method to remap the array arr1
with the helper object obj
:
arr1.map(e => obj[e])
The
.map
method creates a new array with the results of calling a provided function on every element in the calling array.
const arr1 = ["a", "b", "a", "c"];
const obj = {a:1, b:2, c:3, d:4, e:5, f:6};
console.log( arr1.map(e => obj[e]))
Javascript - Replace multiple elements in an array using index
Use Array.fill()
var array1 = ['S', 'T', 'A', 'C', 'K', 'O', 'V', 'E', 'R', 'F', 'L', 'O', 'W'];
array1.fill('X', 3, 10)
console.log(array1)
Replacing objects in array
You can use Array#map
with Array#find
.
arr1.map(obj => arr2.find(o => o.id === obj.id) || obj);
var arr1 = [{ id: '124', name: 'qqq'}, { id: '589', name: 'www'}, { id: '45', name: 'eee'}, { id: '567', name: 'rrr'}];
var arr2 = [{ id: '124', name: 'ttt'}, { id: '45', name: 'yyy'}];
var res = arr1.map(obj => arr2.find(o => o.id === obj.id) || obj);
console.log(res);
How to replace item in array?
var index = items.indexOf(3452);
if (index !== -1) {
items[index] = 1010;
}
Also it is recommend you not use the constructor method to initialize your arrays. Instead, use the literal syntax:
var items = [523, 3452, 334, 31, 5346];
You can also use the ~
operator if you are into terse JavaScript and want to shorten the -1
comparison:
var index = items.indexOf(3452);
if (~index) {
items[index] = 1010;
}
Sometimes I even like to write a contains
function to abstract this check and make it easier to understand what's going on. What's awesome is this works on arrays and strings both:
var contains = function (haystack, needle) {
return !!~haystack.indexOf(needle);
};
// can be used like so now:
if (contains(items, 3452)) {
// do something else...
}
Starting with ES6/ES2015 for strings, and proposed for ES2016 for arrays, you can more easily determine if a source contains another value:
if (haystack.includes(needle)) {
// do your thing
}
Move an array element from one array position to another
If you'd like a version on npm, array-move is the closest to this answer, although it's not the same implementation. See its usage section for more details. The previous version of this answer (that modified Array.prototype.move) can be found on npm at array.prototype.move.
I had fairly good success with this function:
function array_move(arr, old_index, new_index) { if (new_index >= arr.length) { var k = new_index - arr.length + 1; while (k--) { arr.push(undefined); } } arr.splice(new_index, 0, arr.splice(old_index, 1)[0]); return arr; // for testing};
// returns [2, 1, 3]console.log(array_move([1, 2, 3], 0, 1));
Replace array elements without losing reference?
You could splice the old values and append the new values.
function magic(reference, array) { [].splice.apply(reference, [0, reference.length].concat(array));}
var arr = [1, 2, 3], b = arr;
console.log(b === arr); // truemagic(arr, [4, 5, 6]);console.log(b === arr); // should return true
console.log(arr);
function .push keep replacing all elements same as last one in array
This can be a bit misleading in javascript:
this.history.push(this.pv);
You're pushing a reference to the same this.pv
pre-allocated vector
What you are trying to do is something like:
this.history.push(this.pv.copy());
Where you are allocating memory for a completely new p5.Vector
object with the x,y coordinates copied from this.pv
(using the copy() method)
Demo:
let ppp = [];
function setup() {
createCanvas(400, 400);
for (let i = 0; i < 3; i++) {
let p = new Particle();
ppp.push(p);
}
}
function draw() {
background(220);
for (let i = 0; i < ppp.length; i++) {
ppp[i].display();
ppp[i].update();
}
}
function Particle() {
this.pv = createVector(random(width), random(height));
this.history = [];
let rndV = p5.Vector.random2D();
this.spdV = rndV.mult(random(1, 3));
this.update = function() {
this.pv.add(this.spdV);
this.history.push(this.pv.copy()); // replace all vector element
//console.log(this.history);
}
this.display = function() {
fill(30);
ellipse(this.pv.x, this.pv.y, 30);
for (let i = 0; i < this.history.length; i++) {
let trail = this.history[i];
ellipse(trail.x, trail.y, 10);
}
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.1.9/p5.min.js"></script>
Related Topics
How Does Group by Works in Sequelize
Angular:How to Add/Remove Files in the Angular
How to Convert Seconds to Minutes and Hours in JavaScript
How to Set an Iframe Src Attribute from a Variable in Angularjs
Bootstrap Modal Only Showing Backdrop
How to Make a Modal Popup to Take an Input Value Using Jquery or JavaScript
Starting the Week on Monday With Isoweekday()
What Does an Exclamation Mark Before a Variable Mean in JavaScript
Check If a Key Exists Inside a Json Object
How to Get the Average from Array of Objects
No Overload Matches This Call. Type 'String' Is Not Assignable to Type 'Signals'
Fullcalendar - Change View for Mobile Devices
Element Implicitly Has an 'Any' Type Because Index Expression Is Not of Type 'Number' [7015]
How to Change Image When Two Buttons Are Clicked
Next.Js Implement External ".Js" With <Script>
Copy/Paste from Excel to a Web Page
Exclude a Folder from Glob Pattern Matching
How to Check If Prevprops and Nextprops Are the Same in React