0

So I feel like this should be easy, but I can't figure it out.

To simplify, I need to dynamically generate an array. Then I need my code to build a list of objects based off the middle of that array.

array = [a, b, c, d];
start = array[0];
finish = array[array.length - 1];
middle = [
  { middle: array[1] },
  { middle: array[2] }
] 

I need this to be dynamic, so I can't hardcode my middle values due to the array length not being set in stone. I assumed I needed a loop function to iterate through my array, but I've never used this for anything but creating a list in the DOM. I feel like I'm overthinking this or something, because this should be easy... everything I do breaks my code though.

my latest attempt was:

middle = [
  for (i = 1; i < array.length - 2; i++) {
    return { middle: array[i] };
  }
]

I think I get why it doesn't work. It just returns what I want, but I don't think that value ever gets stored.

3 Answers 3

3

Just adjusting @chazsolo's answer to your expected output with a mapping to your target format.

const array = [1,2,3,4,5];
const middle = array.slice(1, -1).map(item => ({middle: item}));
console.log(middle);

Sign up to request clarification or add additional context in comments.

2 Comments

Good call, I didn't match his expected output
Man I feel dumb. Ya, just storing that in a variable, and then running that variable where I needed it was all I needed. I was completely overthinking it. Thanks man.
1

Use slice to grab the values you're looking for

const array = [1,2,3,4,5];
const middle = array.slice(1, -1);

console.log(middle);

This returns a new array containing every value except for the first and the last.


If you don't, or can't, use map, then you can still use a for loop:

const array = [1,2,3,4,5];
const middle = array.slice(1, -1);

for (let i = 0; i < middle.length; i++) {
  middle[i] = {
    middle: middle[i]
  };
}

console.log(middle);

2 Comments

I think the problem with this is I need to format that middle array as an array of objects. I'm not really struggling to get the middle values as much as I'm struggling to reformat the information in a way that the code reads it like the first example.
@sjahan's answer is more complete in that regard. You just need to map each value to your expected format.
0

Define an array and push whatever you want to push into it.

let array = ['a', 'b', 'c', 'd']
let middles = []
for (i = 1; i < array.length - 1; i++) {
  middles.push({ middle: array[i] })
}
console.log(middles)

In case you want to learn more, check Array

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.