I am looking to reorganize the structure of an array.
For example, consider this array [col1,col2,col3,col4]
I want to nest the elements so that the first element becomes a separate array like this
[[col1], [col2,col3,col4]]
I attempted the code below, but it is placing col2 into the first array position
jsfiddle.net/0ht35rpb/57 - visualization of the issue
k['key'] = i
if (i % 2 === 0) {
m.push([k])
} else {
m[m.length - 1].push(k)
}
return m
This is my attempt:
function arrayMaker(menu) {
var l = []
menu.reduce((m, k, i) => {
if (i === 0) {
m.push([k])
} else {
l.push(k)
}
if (i === menu.length - 1) {
m.push(l)
}
console.log("m", m)
return m
}, [])
}
var menu = ["col1", "col2", "col3", "col4"]
var nest = arrayMaker(menu)
console.log("nest", nest)
Here is the complete code block, presenting a seemingly complex solution for a simple problem.
{
lang.menu.reduce((m, k, i) => {
m.push(k)
if (i === lang.menu.length - 1) {
m = [m.slice(0, 1), m.slice(1)]
}
return m
}, []).map((grouped, index) => (
<div key={index} className={index === 0 ? 'main-footer__left' : 'main-footer__right'}>
{
<div className='row grid__row--offset--30'>
{
grouped.map((item, j) =>
<div key={j} className={(index === 0 && j === 0 ? 'large-45 large-centered' : 'large-14 large-offset-5') + ' columns'}>
<h2 className='text--uppercase text--white footer-text'>{item.title}</h2>
{
item.switch
? <p className='text--white grid__row--offset--15 footer-text'>
{
item.children.map(function (child, j) {
return (
<Link key={j} className={'text--white footer-text transition ' + (props.active_language === child.title.toString().toLowerCase() ? activeLang : alternativeLang)} to={urls[j]}>{child.title}</Link>
)
})
}
</p>
: item.children.map(function (child, j) {
return (
<div key={j} className={(j === 0 ? ' grid__row--offset--15' : '')}>
<Link className='text--white footer-text transition' to={child.link}>{child.title}</Link>
</div>
)
})
}
</div>
)
}
</div>
}
</div>
))
}