1

I have an array that contains several anime characters, and I am using a db to store which ones you have like this:

var your_chars = '2,5,7,93'

u have the chars with this numbers! json/array:

"all_units":[
        {
            "name":"",
            "anime":"",
            "star":"0",
            "image":""    
        },
        {
            "name":"Naruto Uzumaki",
            "anime":"Naruto",
            "star":"2",
            "image":""
        },
        {
            "name":"Son Goku",
            "anime":"Dragon Ball",
            "star":"2",
            "image":""
        },
        {
            "name":"Monkey D. Luffy",
            "anime":"One Piece",
            "star":"2",
            "image":""
        },
        {
            "name":"Naruto Uzumaki (Sage Mode)",
            "anime":"Naruto",
            "star":"4",
            "image":""        
        }
    ]

so if u have char 2, u have naruto uzumaki. but I want to make a list of all units you have (being possible to see name and stars) like this:

[2] - Son Goku (2)
[4] - Naruto Uzumaki Sage (4)

[{numer in array}] - {name} - ({stars})

I tried it using 'for(){}' but I didn't get much result :(

summarizing my goal: make a list of chars I own (var in your_chars) and print it

my last try:

(async()=>{
        var fs = require('fs');
        var item = JSON.parse(fs.readFileSync("./utils/itens.json", "utf-8"));//heres json archive
        
        let u = await client.db.get("main", "charsOwned_{user ID}");//this returns: "value":"2,5,6,1" 
        let chars = u.value
        let list = ''
        for(i = 0; i < 30;i++){
            if(chars[i]){
            let c = item.all_units[i].name
            let n_s = item.all_units[i].star
            let s = '<:s_:813141250911633438>';

            list = list + `\n**[\${i}]**・\${c} \${s.repeat(n_s)}`
            }
        }
        console.log(lista)

})()
7
  • 1
    yes, for(){} won't give you the results like that. Can you show us your actual attempt? Commented Jul 1, 2021 at 21:56
  • yeye, I edited the question with my last attempt Commented Jul 1, 2021 at 22:03
  • 1
    in JS the indexing of arrays starts at zero. so the [2] corespond to Son Goku Commented Jul 1, 2021 at 22:05
  • yeye i know, but this dont return the owned chars, Commented Jul 1, 2021 at 22:07
  • @winter I think you're looking to use u.value.split(/,/g) Commented Jul 1, 2021 at 22:09

4 Answers 4

1

First, you have to make an array of your chars. The following will split them to a string array. The "map" will cast them to integer:

var your_char_array = your_chars.split(',').map(parseInt);

Second, assume all_units is stored in the var named all_units. Then do this to get your result:

const finalArray=[];
all_units.forEach((unit,index)=>{
    if(your_char_array.includes(index+1)){
        finalArray.push('['+(index+1)+'] -'+unit.name+' ('+unit.star+')');
    }
})
console.log(finalArray);
Sign up to request clarification or add additional context in comments.

2 Comments

ty, but i have some errors. there are some users who have a unit X, but the unit Y is printed like this: cdn.discordapp.com/attachments/813121117476225056/… son goku is 1, but is printed naruto cdn.discordapp.com/attachments/813121117476225056/…
@winter Well i think you should play with index+1 part. I don't really know how did you store your data...
1

I agree with FMoosavi's answer but it can be done in a different way using filter.

I would have done it like so:

const all_units = [
        {
            "name":"",
            "anime":"",
            "star":"0",
            "image":""    
        },
        {
            "name":"Naruto Uzumaki",
            "anime":"Naruto",
            "star":"2",
            "image":""
        },
        {
            "name":"Son Goku",
            "anime":"Dragon Ball",
            "star":"2",
            "image":""
        },
        {
            "name":"Monkey D. Luffy",
            "anime":"One Piece",
            "star":"2",
            "image":""
        },
        {
            "name":"Naruto Uzumaki (Sage Mode)",
            "anime":"Naruto",
            "star":"4",
            "image":""        
        }
    ];

// We choose chars: Naruto Uzamaki & and Naruto Uzamaki (Sage Mode):
const your_chars = "1,4";

// Split chars into array to get the indices:
const your_char_indices = your_chars.split(",").map((n) => parseInt(n));

// Then filter out your chars to get only the ones you want:
const units = all_units.filter((unit, index) => your_char_indices.includes(index));

// Then finally map into the style you want:
const result = units.map((unit, index) => `[${your_char_indices[index]}] - ${unit.name} - (${unit.star})`);

// Return the result here:
console.log(result)

4 Comments

The reason i didn't do the filter way is the index to the first array will be lost after filter. And no one will know what it was!!
This is true - but in my eyes the end result is what is important. If we can achieve that end result in a nice clean way for a new data request then what the index was no longer matters right? Either way I upvoted your answer also :) Happy coding!
I'm insisting on it because it's also crossed my mind. Your answer shows the correct result because the your_chars is sorted! I mean if it were ="4,1" you wouldn't have correct answer. That's why i didn't use filter. Correct me if i'm wrong. I'm just curious. Thanks
No actually the order does not matter because the filter operation filters out any entry in the array where the index does not match what we provide, it will check in order yes, but it uses includes it will check if the array of indices includes the index of 1 or 4 regardless. So it will iterate through and if the original string was "4,1" or "1,4" does not matter to filter. The end result will be in a different order sure, and if he specifically wanted it ordered by appearance in the original then we can use sort(); but that was not specified.
0

Assuming your_chars holds a value like '2,4,9,99'

 const response = 
        your_chars.split(',')
                  .map(i => ({...all_units[i], position: i}))
                  .filter(({position}) => position < all_units.length)
                  .map(({name, star, position}) => `[${position}] - ${name} (${star})`)

console.log(response);
//  ["[2] - Son Goku (2)", "[4] - Naruto Uzumaki (Sage Mode) (4)"]

You can print a single string with:

console.log(response.join(' '));

Comments

0

It's a simple one-liner:

let mychars = your_chars.split(',').map(n => json.all_units.length>=+n+1 ? json.all_units[+n].name : "").filter(e=>e);

Here it is, broken out with comments

let mychars = your_chars.split(',') 
              // take your list and turn it into an array
               .map(n => json.all_units.length>=+n+1 ? json.all_units[+n].name : "") 
               // map lets us take an array, item by item, manipulate that however we want, and then return it to be the new item in that array
               // this makes sure the number (turned into a number with the +) index exists in your all_data array. If so, return the name, if not return ''
               .filter(e=>e);
               // filter out the empties because (in this case) we're asking it to find index 93, which doesn't exist and will cause an empty array item for us. Filter takes that out.

Note: the array indexes start at zero, and I treated your_chars as actual indexes. If those are not zero-based, let me know and I can adjust this code

var your_chars = '1,4,7,93'

let json = {
  "all_units": [{
      "name": "",
      "anime": "",
      "star": "0",
      "image": ""
    },
    {
      "name": "Naruto Uzumaki",
      "anime": "Naruto",
      "star": "2",
      "image": ""
    },
    {
      "name": "Son Goku",
      "anime": "Dragon Ball",
      "star": "2",
      "image": ""
    },
    {
      "name": "Monkey D. Luffy",
      "anime": "One Piece",
      "star": "2",
      "image": ""
    },
    {
      "name": "Naruto Uzumaki (Sage Mode)",
      "anime": "Naruto",
      "star": "4",
      "image": ""
    }
  ]
}
let mychars = your_chars.split(',').map(n => json.all_units.length>=+n+1 ? json.all_units[+n].name : "").filter(e=>e);
console.log(mychars)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.