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
}
How to replace or update item of array in JavaScript
You might have misused the slice
method, change slice
to splice
works for me:
this.items.splice(index, 1, item)
slice
doesn't trigger view updates according to the documentation here.
Vue wraps an observed array’s mutation methods so they will also
trigger view updates. The wrapped methods are:
- push()
- pop()
- shift()
- unshift()
- splice()
- sort()
- reverse()
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);
Javascript: Efficiently replace Object in Array that has property with specified value in a stateful manner?
One trick I have used when performance is top priority is to store the data in an object with an array of numeric ids to keep track of everything.
Example similar to yours:
var arr = [
{ id: 1, text: 'aaa' },
{ id: 2, text: 'bbb' },
{ id: 3, text: 'ccc' },
{ id: 78, text: 'zzz' }
];
var lookup = arr.reduce((prev, next) => {
prev[next.id] = next;
prev.allIds.push(next.id);
return prev;
}, { allIds: [] });
Now if you know the id you want to replace you don't need to loop at all
lookup[78] = { id: 78, text: 'new!' };
If you do want to loop through the array use the allIds
property
lookup.allIds.forEach(x=> {
let item = lookup[x];
item.text = '';
});
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)
How to replace specific values in array
Try
let array = [1,3,5];let def = {1: "Tree", 3:"Car", 5:"Dog"};
let r= array.map(x=>def[x]);
console.log(r);
How to replace values in an array based on table values?
You can create a mapping dictionary and then apply this mapping to your list. For example:
mapping = dict(table[1:])
out = [[mapping.get(v, v) for v in l] for l in a]
print(out)
Prints:
[[0.5, 0.5, 0.5], [0.5, 5, 0.05], [0.025, 0.005, 0.123]]
Replace items in array with elements from a different set
Code on Javascript:
let array1 = ['a', null, 'c', null, 'e']
let array2 = [1, 2, 3]
let output = []
let cursorPosition = 0; // cursorPosition is a pointer for `array2` index
let nullPositions = []
// find nullable positions; in our case here will be 1, 4
for (let i = 0; i < array1.length; i++) {
if (array1[i] === null) {
nullPositions.push(i)
}
}
// find total expected numbers of arrays from given input and create that array
const totalArray = Math.pow(array2.length, nullPositions.length);
for (let i = 0; i < totalArray; i++) {
output.push([...array1])
}
// replacement logic for the `null` values
for (let i = 0; i < nullPositions.length; i++) {
cursorPosition = 0;
// frequency: how often the cursor needs to change (depends on null position)
let frequency = totalArray / Math.pow(array2.length, i + 1);
let resetCursorPositionOn = frequency;
for (let j = 0; j < output.length; j++) {
if (j < resetCursorPositionOn) {
output[j][nullPositions[i]] = array2[cursorPosition];
} else {
resetCursorPositionOn += frequency;
cursorPosition++;
if (cursorPosition === array2.length) {
cursorPosition = 0;
}
output[j][nullPositions[i]] = array2[cursorPosition];
}
}
}
console.log(output);
Output:
[
["a",1,"c",1,"e"],
["a",1,"c",2,"e"],
["a",1,"c",3,"e"],
["a",2,"c",1,"e"],
["a",2,"c",2,"e"],
["a",2,"c",3,"e"],
["a",3,"c",1,"e"],
["a",3,"c",2,"e"],
["a",3,"c",3,"e"]
]
It works in any number of combinations.
Related Topics
How to Smoothly Scroll to an Element in Pure JavaScript
Sorting Objects by Property Values
What Is the List of Possible Values for Navigator.Platform as of Today
JavaScript .Replace Command Replace Page Text
Find Out How Long an Ajax Request Took to Complete
Canvas Todataurl() Returns Blank Image
Is It Safe to Assume Strict Comparison in a JavaScript Switch Statement
How to Use Nodejs to Open Default Browser and Navigate to a Specific Url
What Is the Dollar Sign in JavaScript, If Not Jquery
How to Access 'Window' (Target Page) Objects When @Grant Values Are Set
How to Remove Element from an Array in JavaScript
Jquery.Getjson - Access-Control-Allow-Origin Issue
Which Browsers Support Import and Export Syntax for Ecmascript 6
Es6 Promise.All() Error Handle - Is .Settle() Needed
Why Does an Onclick Property Set with Setattribute Fail to Work in Ie
Check Whether an Array Exists in an Array of Arrays
Where to Save a Jwt in a Browser-Based Application and How to Use It