change values in array when doing foreach
The callback is passed the element, the index, and the array itself.
arr.forEach(function(part, index, theArray) {
theArray[index] = "hello world";
});
edit — as noted in a comment, the .forEach()
function can take a second argument, which will be used as the value of this
in each call to the callback:
arr.forEach(function(part, index) {
this[index] = "hello world";
}, arr); // use arr as this
That second example shows arr
itself being set up as this
in the callback.One might think that the array involved in the .forEach()
call might be the default value of this
, but for whatever reason it's not; this
will be undefined
if that second argument is not provided.
(Note: the above stuff about this
does not apply if the callback is a =>
function, because this
is never bound to anything when such functions are invoked.)
Also it's important to remember that there is a whole family of similar utilities provided on the Array prototype, and many questions pop up on Stackoverflow about one function or another such that the best solution is to simply pick a different tool. You've got:
forEach
for doing a thing with or to every entry in an array;filter
for producing a new array containing only qualifying entries;map
for making a one-to-one new array by transforming an existing array;some
to check whether at least one element in an array fits some description;every
to check whether all entries in an array match a description;find
to look for a value in an array
and so on. MDN link
Changing a value inside the array in a forEach() loop
Suggestion : move newArray
outside the clicked function as it is going to update on click.
Implementation : You can use Array.filter() method on newArray
to check if record as per the input id is available or not and then by using Array.find() you can do filtering on the mainArray
if there is no data in newArray
.
Live demo :
const newArray = [];
function clicked(inp){
const mainArray = [
{ id: 1, name: "Shoes",stock: 5, price: 10 },
{ id: 2, name: "Bag",stock: 10, price: 50 },
];
const findInNewArr = newArray.filter(item => inp === item.id);
if (findInNewArr.length) {
newArray[0].stock += 1;
} else {
const findInMainArray = mainArray.find(element => inp === element.id);
if (findInMainArray) {
findInMainArray.stock = 1;
newArray.push(findInMainArray);
}
}
console.log(newArray);
}
<button id="1" onclick="clicked(2)">Click me</button>
Why is my forEach loop not editing my array?
The forEach
method of an array does not modify the array, it just iterates over it. When you change the argument in the callback function, that doesn't affect the array either. Also, forEach
doesn't do anything with the return values from the callback. Once you calculate the value you want to use to replace, you can set it using the index and array arguments, like so.
var test = [12, 929, 11, 3, 199, 1000, 7, 1, 24, 37, 4, 19, 300, 3775, 299, 36, 209, 148, 169, 299, 6, 109, 20, 58, 139, 59, 3, 1, 139];
test.forEach(function(element, index, array){ if (element % 3 === 0){ element += 100; array[index] = element; }});
console.log(test);
PHP foreach change original array values
In PHP, passing by reference (&
) is ... controversial. I recommend not using it unless you know why you need it and test the results.
I would recommend doing the following:
foreach ($fields as $key => $field) {
if ($field['required'] && strlen($_POST[$field['name']]) <= 0) {
$fields[$key]['value'] = "Some error";
}
}
So basically use $field
when you need the values, and $fields[$key]
when you need to change the data.
Modify array values in foreach loop
There are 2 ways of doing this
foreach($questions as $key => $question){
$questions[$key]['answers'] = $answers_model->get_answers_by_question_id($question['question_id']);
}
This way you save the key, so you can update it again in the main $questions
variable
or
foreach($questions as &$question){
Adding the &
will keep the $questions
updated. But I would say the first one is recommended even though this is shorter (see comment by Paystey)
Per the PHP foreach
documentation:
In order to be able to directly modify array elements within the loop precede $value with &. In that case the value will be assigned by reference.
PHP - Nested Foreach Change Original Array Values
The first assignment works for me. But you can simplify it by using reference variables for the iteration variables.
foreach($array as &$value) {
foreach($value['customers'] as &$sValue) {
if($sValue['age'] < 35) {
$sValue['isYoung'] = true;
}
}
}
Related Topics
Detect Back Button Click in Browser
Can JavaScript Connect with MySQL
How to Check If an HTML Element Is Empty Using Jquery
Why Does (0 < 5 < 3) Return True
Pick Random Property from a JavaScript Object
How to Close a Browser Window Without Receiving the "Do You Want to Close This Window" Prompt
How to Be Notified When an Element Is Added to the Page
How to "Await" for a Callback to Return
When Is the Comma Operator Useful
Date Constructor Returns Nan in Ie, But Works in Firefox and Chrome
Why Do Results Vary Based on Curly Brace Placement
How to Update an "Array of Objects" with Firestore
Event.Returnvalue Is Deprecated. Please Use the Standard Event.Preventdefault() Instead
Javascript: Operator Overloading
Finding Matches Between Multiple JavaScript Arrays
Are All JavaScript Callbacks Asynchronous? If Not, How to Know Which Are
Calling a JavaScript Function Returned from an Ajax Response