Index inside map() function
You will be able to get the current iteration's index
for the map
method through its 2nd parameter.
Example:
const list = [ 'h', 'e', 'l', 'l', 'o'];
list.map((currElement, index) => {
console.log("The current iteration is: " + index);
console.log("The current element is: " + currElement);
console.log("\n");
return currElement; //equivalent to list[index]
});
Output:
The current iteration is: 0 <br>The current element is: h
The current iteration is: 1 <br>The current element is: e
The current iteration is: 2 <br>The current element is: l
The current iteration is: 3 <br>The current element is: l
The current iteration is: 4 <br>The current element is: o
See also: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array/map
Parameters
callback -
Function that produces an element of the new Array, taking three arguments:1) currentValue
The current element being processed in the array.2) index
The index of the current element being processed in the array.3) array
The array map was called upon.
Array.map : get the index of each element to use in the return function
You can make it cleaner by three steps:
- Use the second parameter of callback passed to
map()
which is index of element. - Use arrow function and implicitly return the value
- Use Template Strings instead of
+
again and again.
var a = [4,7,9];let res = a.map((x,i) => `index ${i} : ${x}`);console.log(res)
How can I pass the index from the filter function into the map function?
If you want to know the index that it had in the original, unfiltered array, then i think the simplest solution is dropping the use of .filter
and using that original array directly, as follows:
{itemArray.map((item, index) => {
if (item.type !== compItem.type) {
return null;
}
return (
<Row>
<Col key={item.name} onClick={(e) => openItemEdit(e, index, item)}>
{item.name}
</Col>
</Row>
);
})}
Javascript - Add Item in the middle of an array inside map function
Preface: You're using map
incorrectly. If you're not using the array that map
builds and returns, there's no reason to use it; just use a loop or forEach
. More in my post here. And one reason to use an old-fashioned for
loop is that you're in control of iteration, which matters because...
However, it's acting weirdly and sometimes I'm getting 2 items being added instead of one.
That's because you're inserting into the array being looped by the map
, so on the next pass, it picks up the entry you're adding.
If you do a simple loop, you can easily avoid that by incrementing the index when you insert, or by looping backward; here's the looping backward approach:
const addItemToLevelTwoArray = (uniqueID, arrayID) => {
const reportObject = {
id: arrayID,
title: "",
};
for (const section of data) {
for (let reportIndex = section.content.length - 1; reportIndex >= 0; --reportIndex) {
const report = section.content[reportIndex];
if (report.id === uniqueID) {
section.content.splice(reportIndex, 0, reportObject);
}
}
}
};
Because we're looping backward, we won't pick up the entry we just added on the next pass.
Since the outer loop doesn't have that problem, I used the more convenient for-of
.
Since you asked about map
, if you do use the array map
returns, you can do this by returning an array with the two entries, and then calling flat
on the array map
builds. (This only works if the array doesn't already contain arrays, because they'll get flattened to.) This is common enough that it's combined in one function: flatMap
. It's not what I'd do (I'd do a loop), but it's certainly feasible. Sticking with forEach
and flatMap
rather than using for-of
and for
:
const addItemToLevelTwoArray = (uniqueID, arrayID) => {
const reportObject = {
id: arrayID,
title: "",
}
data.forEach(section => {
section.content = section.content.flatMap(report => {
if (report.id === uniqueID) {
// Return the new one and the old one
return [reportObject, report];
}
// Return just the old one
return report;
});
});
};
That assumes it's okay to modify the section
object. If it isn't, Alberto Sinigaglia's answer shows creating a new replacement object instead, which is handy in some sitautions.
How can I get the position of an object during map function?
The second parameter for the function provided to map is the current index
of the element
arr.map((item, index) =>{
if(index === arr.length-1)
console.log('last one')
})
map function reducing index not working (with React)
else if (i === 5) { // && character === ".", or else we wouldn't get here
you'll only ever get to that else
if character === "."
, and since i === 4
when that is true, this else might as well not be there. You probably want to reverse the order of all of these checks, if (character === ".") {} else if (i === 5) {} else { /* !== "." */ }
Does time complexity get affected in a map function with index for a large array
That does not impact the time complexity at all - you're looping through the array of length n
once per item, so it's a linear time complexity O(n)
. I'm fairly certain it wouldn't impact performance, &&
short-circuits so it would only be running index == 1
for the rest of the indices. A potentially more performant way to do it would be to handle the first two items outside of the loop, then slice(2)
to get the rest of the array and just run map
on that without the if
statement.
But in short, that if
statement will not noticeably affect performance, and the time complexity is only really affected by how much you're looping through the array (in this case, you're only looping through each element once so it's O(n)
).
i cant access index of map function within function call on button(onClick()), which is within scope of map(),code is below
onClick
doesn't give you the index
. You have to get the index from the map
directly if you use as
<button onClick={(e) => addValueField(e, index)}>
Add another value
</button>;
and you can set variation
state as
const addValueField = (e, index) => {
e.preventDefault();
setVariation((state) =>
state.map((o, i) => (i === index ? { ...o, value: [...o.value, ""] } : o))
);
};
JavaScript Array#map: index argument
The index of the current item is always passed to the callback function, the only difference if you don't declare it in the function is that you can't access it by name.
Example:
[1,2,3].map(function(o, i){
console.log(i);
return 0;
});
[1,2,3].map(function(o){
console.log(arguments[1]); // it's still there
return 0;
});
Output:
0
1
2
0
1
2
Demo: http://jsfiddle.net/Guffa/k4x5vfzj/
Related Topics
Replace All Spaces in a String with '+'
How to Update States 'Onchange' in an Array of Object in React Hooks
Wrapping a Set of Dom Elements Using JavaScript
Accessing the Content of Other Tabs in a Browser
Angularjs Toggle Class Using Ng-Class
How to Wrap an Await/Async Try/Catch Block to Every Function
Jquery Add Required to Input Fields
Dynamic Extension Context Menu That Depends on Selected Text
Can Read-Only Properties Be Implemented in Pure JavaScript
Chart.Js - Drawing an Arbitrary Vertical Line
JavaScript Ie Detection, Why Not Use Simple Conditional Comments
Creating an Array of Cumulative Sum in JavaScript
How Does the Messages-Count Example in Meteor Docs Work
Does a JavaScript If Statement with Multiple Conditions Test All of Them