1

Hi all I have following code: my code

I have following scenario. I am counting all my skill names char length and if that length is greater then 25 I am hiding all rest skills and showing in number how many skills is hided. That part is now working. But when I can't show my visible skills. Can you help me to resolve that problem and optimized my code if you think there is something wrong.

Thank you.

here my skills

    const skills = [
      {
        id: 1,
        name: "Html"
      },
      {
        id: 2,
        name: "css"
      },
 
   ... and so on
];

my code part:

   let lengthCount = 0;
   let maxIndex = 0;
   const skill = [];

   const Skill = () => {
    skills.map((item, index) => {
      if (lengthCount <= 20) {
        maxIndex = index;
        skill.push(item.name); // I am adding items to my skill array
       }
     lengthCount = lengthCount + item.name.length;
    });

    // mapping items from skill array
    let mySkills = skill.map((perSkill) => (
      <span key={perSkill.id} className="element">
        {perSkill.name}
      </span>
     ));
    
    
    return (
      <div className="wrapper">
        <div>{mySkills}</div>+{skills.length - maxIndex - 1}
      </div>
    );

3 Answers 3

1

You're pushing item.name in your skill array. So the array will only contain names and not objects. So print perSkill, and not perSkill.name. If you want skill to be an array of objects, then use:

skill.push(item)

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

Comments

1

You just need to change {perSkill.name} to {perSkill} and it'll work fine

sandbox

Comments

0

I use reduce to loop through you skills, and each step we update object { total, list} if the total + new name length > LIMIT_NUMBER we just return the old one. If not we append new item to the object.list and increase the total.

const LIMIT_NUMBER = 5
const skills = [
      {
        id: 1,
        name: "Html"
      },
      {
        id: 2,
        name: "css"
      }]
      
const newSkillList = skills.reduce((acc, curr) => {
   if (acc.total + curr.name.length > LIMIT_NUMBER){
      return acc
   } else{
      const total = acc.total + curr.name.length
      const list = [...acc.list, curr]
      return {list, total}
   }
},{list:[], total: 0})
console.log(newSkillList)

Comments

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.