four-eyes
four-eyes

Reputation: 12394

Check on array created in map()

map() returns an array as a result (resultArr). Is it possible to perform checks on the 'intermediatly' created array (intermediateArr) within the map function? Somewhere, the resultArr muste be stored so that the results of the map() function can be concatenated or something. Is it possible to access it?

Let's assume I want to push values to an array, if they are not included. I could do something like

someArr.map(item => {
    let resultArr= [];
    if(!resultArr.includes(item)) {
        resultArr.push(item);
    }

However, map already creates an array. It would be a 'waste' not using it. So something like

const resultArr = someArr.map(item => {
    if(!intermediateArr.includes(item)) {
        return item
    }

Where intermediateArr is the Array that gets updated after each iteration from the map() function, the array, that finally is resultArr

Upvotes: 0

Views: 82

Answers (4)

Nina Scholz
Nina Scholz

Reputation: 386560

For getting unique values, you could use a Set.

var array = [1, 2, 3, 1, 2, 4, 5],
    unique = Array.from(new Set(array));

console.log(unique);

Upvotes: 2

Luca Kiebel
Luca Kiebel

Reputation: 10096

You can use Array#reduce((intermediateArr, el) => {}, []) instead, where intermediateArr is the array that is build up while the function is running.

If for example you want to check the items in every iteration, you could use something like this:

let someArr = [1,2,2,2,3,3,4,4,5,5,6,7,8,9]


let resultArr = someArr.reduce((intermediateArr, item) => {
    if(!intermediateArr.includes(item)) {
        intermediateArr.push(item)
    }
    return intermediateArr;
}, [])


console.log(resultArr.toString())  // 1,2,3,4,5,6,7,8,9

Upvotes: 0

Nikhil Aggarwal
Nikhil Aggarwal

Reputation: 28455

Rather than map, you can simply use a for loop to access the intermediately created array.

let someArr = [1,2,4,1,5];
const resultArr = [];
for(let item of someArr) {
  if(!resultArr.includes(item)) resultArr.push(item);
}
console.log(resultArr);

Upvotes: 0

deceze
deceze

Reputation: 522032

No, the "intermediate" array is internal to the map implementation.

You can however use reduce for what you want. A map explicitly maps each element of an array to another value; the result always has the same length as the input. A reduction is very explicitly what you're looking for; you reduce or transform the array into something else.

someArr.reduce((acc, item) => {
    if (!acc.includes(item)) {
        acc.push(item);
    }
    return acc;
}, [])

Upvotes: 2

Related Questions