Possible to Reverse .forEach()?


#1

So I’ve been working on another classic beginners’ exercise, displaying array elements in reverse order without altering the string itself (why is there this stipulation, though? Is it somehow even easier to accomplish by altering the string itself?? Sounds like that should be harder, if anything…)

I’ve figured it out in “only” eight minutes (!) but I did get to wondering: would it be possible to use .forEach() somehow?

The only thing I could think of is

arr.forEach(function(elm, ind) {
		console.log(elm[arr.length - ind]);
	});
}

where elm[arr.length - ind] would evaluate to, for example, “element-index-zero-subtracted-from-array-length-ten-equals-ten-so-iteration-starts-at-last-element”…except JavaScript won’t cooperate! :slight_smile:

So it looks like it’s impossible to use .forEach() in reverse…or is it?

Anyone else wanna unleash his/her inner Rube Goldberg on this?? :wink:


#2

You could start with figuring out how to print the first element, I’m seeing a bit of “spray and pray” in that code, keep in mind that it is you who are controlling everything going on there, not javascript, it’s you who make things align. If they don’t align then take a few steps back and look at what you have and adjust.
I wouldn’t use foreach and then ignore each value
Looping backwards in javascript - very much something that can be googled

This looks the same to me as += earlier
Don’t write something and then wonder why it doesn’t work. You need a higher degree of control and responsibility over what you write. If you understand and see each part then you can fix it. If you don’t then you have the information of which part to learn about.


#3

Like we said earlier, “to a hammer, everything is a nail.” Examine the intent of the array method, forEach()… to facilitate running a function on every element in the array. One operative word there is, every. There is no break in a forEach loop. If anything this is not a utility function, but a specialized tool.

What you are asking the method to do is way beneath its qualifications. It is not a straight swap with, for (...) {}, the more viable tool for the job in this instance. Forgive me if I don’t even discuss your code, which is, frankly, off the mark. In archery they call this a sin but in programming it’s HACF worthy. Fortunately we always get another crack at the problem.

Let’s say we have a list, and we want a reverse representation of that list. We have no other tool but an index, and a length property. What will result will be repetitive, but it will give us some insight.

Reversing a list is essentially pivoting it 180 degrees if we view it as a vector. There is one special condition, odd (length) lists pivot around the actual middle data point which does not move; even lists pivot around a point between the two middle data points.

Given the length, we can find either pivot point.

const list = ['a', 'b', 'c,', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm'];
var pivot = Math.floor(list.length / 2)  // an integer
var x1, x2, r;
if (list.length % 2) {
    x1 = pivot - 1;
    x2 = pivot + 1;
} else {
    x1 = pivot - 1;
    x2 = pivot;
}
r = list[x1]
list[x1] = list[x2]
list[x2] = r
x1 = x1 - 1
x2 = x2 + 1
r = list[x1]
list[x1] = list[x2]
list[x2] = r
x1 = x1 - 1
x2 = x2 + 1
r = list[x1]
list[x1] = list[x2]
list[x2] = r
x1 = x1 - 1
x2 = x2 + 1
r = list[x1]
list[x1] = list[x2]
list[x2] = r
x1 = x1 - 1
x2 = x2 + 1
r = list[x1]
list[x1] = list[x2]
list[x2] = r
x1 = x1 - 1
x2 = x2 + 1
r = list[x1]
list[x1] = list[x2]
list[x2] = r
console.log(list);    //  ["m", "l", "k", "j", "i", "h", "g", "f", "e", "d", "c,", "b", "a"]

#4

What?? How’s that à propos of anything…of course I can get the first element; that’s the natural operation of .forEach(), to start with the first element!

Or do I misunderstand what you mean…?

LOL – “spray & pray” is exactly my programming paradigm! But it’s interesting you see the programmer as being in control when to me I feel like I’m trying to instruct an alien being in a pidgin between natural language and mathematics!

BTW, are you are aware of this; it’s a great read:

Actually, I didn’t see anything about iterating backwards using .forEach().

REALLY??? THAT FUNDAMENTAL???

BTW, “the += affair” earlier was just brain-fog – as was way back with me trying to parseInt() something after first converting it to a string (ridiculous!)…but I don’t think it’s simple lack of sleep this time. I’ve never seen .forEach() being made to iterate backwards over an array – backwards, mind you – and I was curious whether it could be done.

Well, I’d thought that my arr.forEach(function (elm, ind)elm[arr.length - ind] would evaluate, in the case of a ten-element array, for example, to “ element-index-zero-subtracted-from-array-length-ten-equals-ten-so-iteration-starts-at-last-element but unfortunately that’s not how JavaScript interprets it!

Well, sure – but how to “bell the cat” is the issue, isn’t it?

Though I’m not sure about “responsibility”…if something doesn’t occur to someone – if you just don’t think of something – how’s it a matter of “responsibility”?? I can study day after day, coding and coding, but if something doesn’t occur to me, I’m not sure how it could be considered a matter of responsibility or lack thereof.

Of course, please explain your “philosophy of learning” if I’ve mischaracterized it.


#5

Huh? What’s the difference?? I actually don’t know why .forEach() was introduced – I like that the abstraction takes us out of playing with loops and their counters, but was that the only reason, to make things simpler to accomplish?

If so, that sounds very “utilitarian” to me!

Oh, my! That’s quite funny, actually – for all the coding faux-pas…I had thought I was maybe “breaking” it instead by trying to have it do something that seems the opposite of its whole raison d’être!

LOL, well, yeah, but the question is why it didn’t work…the logic to me seemed correct – though obviously that’s not how the language works (cf. idioms, like “mind your own onions” in French).

Sorry, that does not “compute” for me! :wink:

Really, I don’t know what your code means at all…thanks, though – I’ll look up “lists” and “pivots” now…

BTW, you did hear me say at the outset that I reversed the array relatively easily, right?

var arr = ["a", "b", "i", "n", "x", "y", "z", 0, 1, 42];

for (let i = arr.length - 1; i >= 0; i--) {
	console.log(arr[i]);
}

#6

BTW, I should also ask: why does it not matter at all whether i is arr.length - 1 or just arr.length???


#7

Clearly I missed that, and don’t really feel any pangs for having done so. In most cases it seems you have your mind made up and have pretty much lost my interest. Sorry to say.


#8

Whiich is not constrained to order. forEach treats a collection like a dictionary (object) not like an array.

Basically, we’re on our own and have to sort out our own problems. The choice is simple, reach to our own brain and determination or reach to the internet for a handy solution or at least explanation of what we are pursuing. Bottom line, it’s on us. Treat the help you get with more respect or expect less of it.


#9

Responsibility and control are two sides of the same coin, I mean that it’s up to you to observe what happened and adjust it to better suit you.

You do some math and come up with an index. What if you replaced that with 0? You won’t get the first element. There’s no magical vision I’ve got here to spot that, it’s just reading through it and processing it, again, control and awareness

And my philosophy here is that of learning one piece at a time until full understanding so that whenever something is wrong about it everything needed to fix it is known, and so that individual parts can be reasoned about when they are combined to make bigger things

gotta go, finish later


#10

It would matter. Therefore you can conclude that you’re not doing that
Looking up a value by location in an array is a simple matter and that means you can create a simpler piece of code where you only do that, and compare to what you do there

There’s no reason to stare blankly and wonder what’s wrong. Ask yourself what needs to happen and then check that all those things are happening, observe. It’s not like the program will hide any information from you - you wrote it


#11

Um, I have no idea what you’re referring to with “you have your mind made up”…I’m just asking questions here.


#12

Huh??? Why would it ignore the order of things, considering that it’s applied to arrays???

Dude, what???

I don’t even…

This is a public forum, right? I’m just askin’…what’s the problem??

Where did I disrespect anyone???

WTF???

Man, I can’t…I can’t even…


#13

Well, I don’t know what happened. That’s why I’m asking. What are these forums for, then??

You speak very obliquely, circumspectly, and I just don’t know how to parse what you’re saying.

  1. I’m asking a specific question.
  2. You’ve since gone alluding to some wider issue of which I’m not aware – something about my “responsibility” to, I guess, magically know the answer to what I’m asking about!

Now here’s how I “parse,” as I say, the situation:

  1. I’ve been checking out this matter of .forEach() and, namely, its first two parameters – elm and ind, as I’ve designated them here – not behaving the way I had expected. The crux of the matter simply seems to me now that I cannot use the second parameter in the way of an array[i] – where I can do an array[arr.length - 1] – which is what my elm[arr.length - ind] was all about.

So I would have expected a discussion about why the two “things” are not similar – under-the-hood stuff like “shallow” and “deep” copies (A.K.A. cloning)…which, incidentally, I happened upon while researching the answer to my question (whether .forEach() can be used in a reverse order) – it can be, using .splice() just so:

var arr = [1, 2, 3];

arr.slice().reverse().forEach(function(x) {
    console.log(x);
})

Not discourse on a student’s morality!


#14

Why don’t you just answer the question if you’ve got time for a diatribe??

Or tell me what these forums are for – or better yet, ignore me; I’ll go away if these forums provide no value.

Y’all act like I’m keeping youse awake or something…sheesh…


#15

We’re just trying to keep track of how many unresolved topics you still have going. You’re all over the map, and making it hard to know how to respond. Better that we focus on something until it is resolved so we can move on. Your topics are like open tickets on a help desk. We need to put some of them on the peg.


#16

So say that instead of accusing me of being irresponsible or disrespectful! I hate character assassination…

I’m “all over the map” since I’ll get “inspired,” so to speak, by a simple exercise and start thinking about what else I could do or should be able to do…the stuff I ask about here is almost always stuff I can’t think any further about (in the beginning there was one or two posts about things I forgot to google myself)…here’s my screen at any one time:

See all those tabs? They’re research I’m conducting on this, that, and the other – including all the stuff you mentioned to look into (most recently “lists” and “pivots”)…

What can I say, I’m curious. Sorry if that messes up your workflow…

Speaking of which: I thought you guys are volunteers…am I right? Like, it’s not like y’all are paid by how many threads you wrap up…or does Codecademy expect you people to be working just like you were paid (unfortunately not unimaginable in this “post-industrial capitalism” of ours)…


#17

Please point that out. We were talking about the responsibilty of a programmer to therr own outpourings. They work or they don’t. It had nothing to do with forum behavior.

Yes. Why I asked you to treat us with tender hands. If you are listening to Agnes Obel like I am right now you would be feeling the caress.

I only have to get involved in about ten or so threads a day to get over-stimulated. It gets vented in noise and country quiet, some random, some orderly. It’s an autistic thing, perhaps but I’m far too old to be worrying about that. They should have caught it half a century ago instead of calling it spastic.


#18

Uh, it’s .slice(), no “p,” just as the quoted code actually uses.


#19

What?? You don’t remember your own

???

How am I being disrespectful of assistance rendered???

Indeed, how am I irresponsible for my “outpourings” here???

If I don’t know something, I ask. What’s the problem? You think I’m asking 'cause I’m testing you or something??

But how have I been “rough” or otherwise “not tender” in my asking my questions???

Sorry; what does that mean, exactly? I get the sense it becomes unpleasant for you but I don’t understand what exactly or why…

Not getting your oblique references at all…please explain.


#20

You want to make this about yourself, rather than codng; that is clear. Can’t abide by that.