forEach loop through two arrays at the same time in javascript
Use the second parameter forEach
accepts instead, which will be the current index you're iterating over:
n = [1,2,3,5,7,8,9,11,12,13,14,16,17,18,20,21,22];
n.forEach((element, index) => { console.log(element, index);});
For Loop with two array in javascript
You can do something like this:
var html ='';
var option = [ ['meal', 'big', 'medium', 'small'], ['drink', 'big', 'medium' ]];
for (var i = 0; i < option.length; i++){ var option_type = option[i]; html += '<div>' + option_type[0] + '</div>'; for(var j = 1; j < option_type.length; j++) { html += '<span>' + option_type[j] + '</span>'; } }
document.getElementById('container').innerHTML=html;
#container span{ display:inline-block; margin-right:10px; border:1px solid #333; padding:10px;}
<div id="container"></div>
Combining two arrays in JavaScript with for loop
1) declare the two arrays, especially the numbers one (possibly with the dot operator?)
You mean create rather than declare (you don't declare arrays in JavaScript, because it's a loosely typed language). Yes, you can use an array literal:
var letters = ["a", "b", "c", "d"];
or split
:
var letters = "abcd".split("");
...though whether split
is "smarter" is a matter of opinion. :-)
You can also use the mapping feature of Array.from
:
var letters = Array.from(Array(4), (_, index) => String.fromCharCode(97 + index));
But that might be a bit overdoing it. It makes more sense for the numbers one as you mentioned:
var numbers = Array.from(Array(6), (_, index) => index + 1); // Note I've renamed it to be plural
2) combine the string elements of these two arrays into the combined one without using an old fashioned for loop, perhaps with Array.map() or Array.from()?
A for
loop is simple and clear, but for-of
would probably be even simpler and clearer:
for (const letter of letters) {
for (const number of numbers) { // Note I've renamed the `numbers` array to be plural
combined.push(letter + number);
}
}
Although you could shoehorn it into an Array.from
by doing math on the index, to me it would be overcomplicated.
for-of
and Array.from
are both new(ish) as of ES2015 (aka "ES6"), so be sure to check your target environments for support, and/or use transpiling (for for-of
) and a polyfill (for Array.from
).
Looping over two arrays in javascript simultaneously
Turn the first array into an object indexed by id
first, so you can look up the appropriate matching object in O(1)
time, and then you can .map
the selectedList
:
const masterList=[{id:1,name:'Abc'},{id:2,name:'Def'},{id:3,name:'Ghi'}];const selectedList=[2,3];
const masterById = masterList.reduce((a, obj) => { a[obj.id] = obj; return a;}, {});
const desiredList = selectedList.map(id => masterById[id]);console.log(desiredList);
looping through 2 arrays
You don't want a nested loop - you simply need to link the i
th item in links
to the i
th item of hrefLinks
. With forEach
, you can do this just by using the second argument to the callback, which will refer to the current index being iterated over:
const list = document.body.appendChild(document.createElement('ul'));
const links = ['Home', 'Contact', 'About'];const hrefLinks = ['/', 'contact', 'about'];
links.forEach((linkName, i) => { const li = document.createElement('li'); const a = document.createElement('a'); a.href = hrefLinks[i]; a.textContent = linkName; li.appendChild(a); li.className = 'nav-link'; list.appendChild(li);});
Looping over two arrays of object to loop for matching ids. Then return a new array of custom objects based of custom values
You can map
over the array and use Array.find
to get the item in contacts
whose phoneNumber
property is either the current item's to
or from
property. If an item is found, assign the item's name
property to the current item's displayName
property:
To implement a default display name, we can remove the if
statement and use a ternary operator to assign the name
property if an item was found, and otherwise assign the default display name.
const myNumber = '69';
const contacts=[{phoneNumber:"420",name:"Mike Smith",favorite:!1,color:"orange"},{phoneNumber:"360",name:"John Smith",favorite:!0,color:"green"}];
const messages=[{to:"69",from:"360",isRead:!1,time:new Date,owner:0,message:"Hello there friend this is walker"},{to:"69",from:"360",isRead:!0,time:new Date,owner:1,message:"Hello there friend this is walker"},{to:"69",from:"720",isRead:!1,time:new Date,owner:0,message:"Hello there friend from random person"},{to:"69",from:"720",isRead:!0,time:new Date,owner:1,message:"Hello there friend from random person"}];
let defaultDisplayName = 'Spectric'
const result = messages.map(e => {
let found = contacts.find(f => [e.to, e.from].includes(f.phoneNumber))
e.displayName = found ? found.name : defaultDisplayName;
return e;
})
console.log(result)
Related Topics
Pdf Blob - Pop Up Window Not Showing Content
Change Specific Button Text on Click Inside Ngfor
Download Image as File in Typescript
Write a Auto-Fill and Submit Web Form Program
Javascript: How to Read a Hand Held Barcode Scanner Best
How to Remove Captcha Verification from Firebase Phone Auth Using JavaScript
Remove Time from Gmt Time Format
Resize a Base-64 Image in JavaScript Without Using Canvas
Concatenating Variables and Strings in React
How to Remove HTML Element from Dom With React
Expected Linebreaks to Be 'Lf' But Found 'Crlf' Linebreak-Style
Slick Carousel - Force Slides to Have the Same Height
Javascript Restrict Text Field to Numbers and Decimals
How to Add Button on Each Row in Datatable
If a Div Contains a Specific String of Text, Edit the Parent'S CSS
How to Delete Specific Item from Localstorage