0

I have following code: my code

I need to check if my elements name.length sum count is greater than 25 then only show items whose name.length sum is less than 25. And also print count of items which are not shown.

I am trying something like this, but I stuck, please help :)

    const skills = [
    {
      id: 1,
      name: "Html"
    },
    {
      id: 2,
      name: "css"
    },
    {
      id: 3,
      name: "bootstrap 4"
    },
    {
      id: 4,
      name: "scss"
    },
    {
      id: 5,
      name: "JS"
    },
    {
      id: 6,
      name: "React"
    },
    {
      id: 7,
      name: "Jquery"
    },
    {
      id: 8,
      name: "Vue JS"
     }
     ];
      return (
        <div>
          {skills.map((skill) => (
        <li key={skill.id}>{skill.name}</li>
      ))}
      {/* with this line I am wanting to show each elemet char count  */}
      {skills.map((skill) => (
        <div>{skill.name.length}</div>
      ))}
      {/* need to show hide elements count  */}
      <div>+{count}</div>
    </div>
  );

In the end I need to get view like this

  • Html
  • css
  • bootstrap 4
  • scss
  • JS

+3

2 Answers 2

1

Well you can approach this as:

let lengthCount = 0;
let maxIndex = 0;

skills.map((item, index)=>{
 if(lengthCount <= 25 ){
   maxIndex = index;
   console.log("item: " , item.name)
 }
  lengthCount = lengthCount + item.name.length;
})

console.log("+",skills.length - maxIndex, " more");

Result:

enter image description here

Here is the link to codepen https://codepen.io/the_only_yasir/pen/dyOdZZR?editors=0010

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

Comments

0

You can do it like this.

 return (
    <div>
      {skills.map((skill) => {
        if (skill.name.length < 25) {
          return <li key={skill.id}>{skill.name}</li>;
        } else {
          countMoreThan25++;
        }
      })}
      +{countMoreThan25}
    </div>
  );

Here is the code for reference. https://codesandbox.io/s/jolly-newton-qjxpw?file=/src/App.js:549-799

2 Comments

Didn't he want to check total sum of names of items, and if that sum is less than 25?
Looking at the output I thought he wants to show the items if its char count is less than 25 else he want to show as "+{items} more" which have char count more than 25.

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.