Home > Software design >  Javascript map through array and look if values exists in that same array
Javascript map through array and look if values exists in that same array

Time:09-11

My question is very simple.

Is it possible to determine whether a new array that is made from an existing one using .map() already has some values?

E.g. I have an array of numbers. I create a new array of objects (the name of the number and the number itself). Since the number 2 occurs twice, I want to create an object with {string: "two double" .... } when the number appears again during mapping.

Is there a way to make this functional without building an empty array and pushing everything in there?

const data = [1, 2, 3, 2, 4];
type NewData = {
    string: string;
    number: number;
};

const test: NewData[] = data.map((data) => {
    return { string: data.toString(), number: data };
});

What I get [
{string: "1", number: 1}
{string: "2", number: 2}
{string: "3", number: 3}
{string: "2", number: 2}
{string: "4", number: 4}

]

 What I wish :) [
{string: "1", number: 1}
{string: "2", number: 2}
{string: "3", number: 3}
{string: "2 is already there", number: 2}
{string: "4", number: 4}  
]

CodePudding user response:

look back at the items that you iterated through til now iterartedElement if this subarray contains the current element then you mark it as duplicate.

const data = [1, 2, 3, 2, 4];

let result = data.map((e,i,data) => {
    let iterartedElement = data.slice(0,i)
    
    return { string: iterartedElement.includes(e) ?`${e} is already there` :e.toString(), number: e };
});

console.log(result)

CodePudding user response:

Using set for more time efficiency -

const data = [1, 2, 3, 2, 4];

type NewData = {
    string: string;
    number: number;
};

let set = new Set(data);

const test: NewData[] = data.map((element, key) => {
    if (set.has(element)) {
        set.delete(element)
        return { string: element.toString(), number: element };
    }
    else {
        return { string: `${element} is already there`, number: element }
    }
);

    

console.log(test)
  • Related