Can someone help me understand this code.

[1,2,3,4]
.filter(idx => idx !== index)
.forEach(idx => {
console.log(idx);
$w(‘#fold’ + idx).collapse();
$w(‘#arrowDown’ + idx).hide();
$w(‘#arrowRight’ + idx).show();
})

  1. What is the [1,2,3,4]? Is it an array? I saw nothing declaring it. And why can it be chained to the filter function?
  2. Could anyone please explain this code above?. The original code is down below or could be found here: https://www.wix.com/code/home/example/Collapse-Elements
  • From what i tried to understand is that a set of numbers is passed into the filter function, and depending on the value of the index, idx will not match 3 numbers out of 4. And for those idx numbers not matching the index number, stuff will happen to them.
    -What id being produced out of the .filter function?
    -In general, I somewhat get what is happening. I just what to get clearer understanding.

function toggleFold(index) {
let $fold = $w(‘#fold’ + index);
let $arrowDown = $w(‘#arrowDown’ + index);
let $arrowRight = $w(‘#arrowRight’ + index);
// toggle the fold at the index
if ($fold.collapsed) {
$fold.expand();
$arrowDown.show();
$arrowRight.hide();
}
else {
$fold.collapse();
$arrowDown.hide();
$arrowRight.show();
}
// collapse the other folds
[1,2,3,4]
.filter(idx => idx !== index)
.forEach(idx => {
$w(‘#fold’ + idx).collapse();
$w(‘#arrowDown’ + idx).hide();
$w(‘#arrowRight’ + idx).show();
})
}

export function headerBox1_onClick(event) {
toggleFold(1);
}

export function headerBox2_onClick(event) {
toggleFold(2);
}

export function headerBox3_onClick(event) {
toggleFold(3);
}

export function headerBox4_onClick(event) {
toggleFold(4);
}

export function headerText1_onClick(event) {
toggleFold(1);
}

export function headerText2_onClick(event) {
toggleFold(2);
}

export function headerText3_onClick(event) {
toggleFold(3);
}

export function headerText4_onClick(event) {
toggleFold(4);
}

Hello,

[1,2,3,4] is an array and it does not need to be declared as it is not a variable or function. It is just an array of numbers that is created every time this function is called. In the code above it is used as indexes for the drop down items (1 is the first drop down item, 2 is the second and so on…)

.filter() is a javascript function that filters data based on the criteria that you give it. In this case it is filtering all the numbers that do not equal the index (index is the index of the dropdown item clicked)

.foreach() i s chained after the filter to collapse/hide the filtered items (which are the other drop down items that were not chosen).

MDN is a great resource to learn and experiment with functions you have not yet come across, check it out and search when your feeling stuck: https://developer.mozilla.org/bm/docs/Web/JavaScript

Hope this helps,
Majd