2

Strange issue on join. It works on initial array, but not with filtered array. Tested also functions for string, but resultA is not string also.

What is wrong with the code:

const constants = [2, 2, 4, 2, 6, 4, 7, 8];
const stdFound = [];

// Makes list of indexes - positions from matching value 2 in constants
constants.filter(function(elem, index, array) {
  if (elem == (2)) {
    stdFound.push(index);
  }
});

//Makes new array from results by indexes found
const resultA = [constants.filter((x, i) => stdFound.includes(i))];
document.getElementById("resultA").innerHTML = resultA;
//Makes string by join
document.getElementById("resultJ").innerHTML = resultA.join(" x ");
<p> ARRAY : <span id="resultA"></span>
  <p> JOIN x : <span id="resultJ"></span></p>

Right now, this code results: ARRAY : 2,2,2 JOIN x : 2,2,2

so clearly, join is not working.

1
  • resultA is an array containing one array. If you console.log it, you will see that resultA === [[2,2,2]]. Therefore, when you joint it, it just gives [2,2,2]. "join is not working", it is. Your dataset is wrong, is all. constants.filter returns an array, and you are encapsulating it inside [ ], creating an array of one array. Commented Oct 8, 2021 at 9:03

1 Answer 1

2

filter() already returns an array. No need to wrap in this [].

console.log(resultA) will show that.

const constants = [2, 2, 4, 2, 6, 4, 7, 8];
const stdFound = [];

// Makes list of indexes - positions from matching value 2 in constants
constants.filter(function(elem, index, array) {
  if (elem == (2)) {
    stdFound.push(index);
  }
});

//Makes new array from results by indexes found
const resultA = constants.filter((x, i) => stdFound.includes(i));
document.getElementById("resultA").innerHTML = resultA;

//Makes string by join
document.getElementById("resultJ").innerHTML = resultA.join(" x ");
<p> ARRAY : <span id="resultA"></span>
  <p> JOIN x : <span id="resultJ"></span></p>

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

2 Comments

Thank you Jeremy Thille and Tushar Shahi! Issue resolved, it was double [[]].
Sure. Use the greentick to mark this as accepted to complete the question

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.