How to find duplicate values in object and push in array to create distinct array of objects in Angular8

I am getting below response from API, but i want to format it for iteration to reach the correct values.

In below objects, i am getting column makeLineName and based on this column, i want to create one types array and push whole object as it is on types array.

Suppose for ex – In below response, We have 2 objects for “makeLineName”:”Red”, So i want to create one types array and push all object inside types array whose matching makeLineName = Red. Thats it.

const data = [{
"makeLineName":"Red",
"country":"Germany",
"processTypeId":"3",
"processTechType":"Batch & crunch"
},
{
"makeLineName":"Red",
"country":"Germany",
"processTypeId":"3",
"processTechType":"Batch"
},
{
"makeLineName":"Blue",
"country":"India",
"processTypeId":"3",
"processTechType":"Continues"
}
];

Expected Output

const data = [{
"makeLineName":"Red",
"country":"Germany",
types :[{
"makeLineName":"Red",
"processTypeId":"3",
"country":"Germany",
"processTechType":"Batch & crunch"
},
{
"makeLineName":"Red",
"processTypeId":"3",
"country":"Germany",
"processTechType":"Batch"
}]
},
{
"makeLineName":"Blue",
"country":"India"
types :[{
"makeLineName":"Blue",
"country":"India",
"processTypeId":"3",
"processTechType":"Continues"
}

}];

I did below code, it was working fine, but it is creating many nested arrays for types and because of this i am facing issue in iterating with loop to get the perfect value of types array.

getMakeLineMasterData() {
    const data = {
      data1: 'India'
    };  
    this.testfile.getWork(data).pipe(map(data => this.processData(data))).subscribe((resp: any) => {
      if (resp) {
        console.log(this.dataSource, "resp");
      }
    });
  }
  processData(data: any) {
    let mappedData = [];
    for (const item of data) {
      const mitem = mappedData.find(obj => obj.makeLineName == item.makeLineName);
      if (mitem) {
        mitem['types'].push(item);
      } else {
        let newItem = item;
        newItem['types'] = [item];
        mappedData.push(newItem);
      }
    }   
    return mappedData;
  }

Right now my code is working and returning data but it is creating many nested arrays for types inside and inside likewise..
Can anyone help me to make it proper as per my expected output.

javascript global variable undefined when calling inside the new, additional function

Coding linting with JS to iterate through a text.
I have a few iterations that count a specific conditions, for example
sentences
are set to be added upon when there is ‘.’ or ‘!’.

However, when I created a function that would print one string with information about number of sentences, overused words and so on, it shows up as undefined… Here’s a piece of code

console.log(betterWords.length);
let counter = 0;

for (let i = 0; i < betterWords.length; i++){
  if (betterWords[i] === 'really' || betterWords[i] === 'very' || betterWords[i] === 'basically'){
    counter++
}
}
console.log('You used overused words ' + counter + ' times.');

let sentences = 0;

betterWords.forEach (word => {
  if (word[word.length-1] === '.' || word[word.length-1] === '!'){
    sentences++
}
});

console.log('There are ' + sentences + ' sentences');
numberOfWords = betterWords.length;

const printFunction = (betterWords, counter, sentences) => {
  return('The number of words in text is ' + numberOfWords + ' There are ' + sentences + ' and overused words are used ' + counter + ' times.');
};

console.log(printFunction());

Output
182
You used overused words 8 times.
There are 12 sentences
The number of words in text is 182 There are undefined and overused words are used undefined times. I am mentioning sentences as one example here. One can see that numberOfWords give a proper output

As one can see once sentences return 12, the other time it’s undefined.

How to make in Cypress an equivalent of PressKeyCode from Appium?

Today i meet a problem with a particular input, it looks like that :

enter image description here –> enter image description here

The problem with this input is that it’s an input with 6 input in it, so a typical cy.get('element').type(aValue) is not working.
I tried to loop on each of the 6 inputs, but it’s not working either.

It seem that the value are not writed like it should be on other normal input (like a textArea) but it show me a “click” on each input.
(This solution : cy.get('element').invoke('val', aValue) doesn’t work either but it show the number on each input but disappear when i want to validate the entry)

Before using Cypress, i was using Appium and i was just looping like that driver.pressKeyCode(charValue) over the value (i didn’t select any element to press the code like it could be here : https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/keyCode) and it worked fine.

But right now this solution doesn’t work with Cypress. Or i just don’t understand how this solution https://sqa.stackexchange.com/a/46913 works, i tried different behaviour and nothing worked for my particular case.

Anyone have an idea to overpass this problem with my input or any solution to make the same thing as i did with Appium ?

What string method for matching specific strings in Javascript

This might be a simple duplicate question but I couldn’t find any solution that resolve my case below. Please help me out! 🙂

TL;DR:

I’m looking for a string method to check if the value matches a specific string and return that result.

I have 3 values which are strings: "$", "$$" and "$$$"

Currently using the .includes method and not getting the result I want. It includes all the results that contain a character from the string -> I only want them to return the results with exactly the value of strings above.

Please check SearchFilter.js component code below.

Ex: If a user chooses “$” from the priceDropdown, it will only return
the dishes with priceRange = “$”.

Explain:

  • Inside this Dinner.js, I have a foodList state which is an array that contains all of the data of food from a MongoDB collection (foodName, isVegetarian, priceRange).

  • And a Search.js component which has: a search input for foodName, a dropdown for priceRange, a dropdown for isVegetarian option.

If a user searches for the text: “pasta”, price range option: “$$”,
vegetarian option: “yes”.

  • It will filter from the foodList array and only return the dishes with those choices included.

-> The problem is in how I’m currently returning the value from the data’s priceRange that includes the value from the priceDropdown that the user chose.

  • If they choose “$” from the priceDropdown, it will return all the results with “$” included (including “$$” and “$$$” options).

  • If they choose “$$” value from the dropdown, it will return the results of “$$” and “$$$


**Question:**

What string method to use to make it only return the results with the right specific string?

Ex: If a user chooses “$” from the priceDropdown, it will only return
the dishes with priceRange = “$“.


**Here are my code:**

**Dinner.js component**:

    import SearchFilter from "SearchFilter.js"
    export default function Dinner() {
    
      const [foodName, setFoodName] = useState('')
      const [isVegetarian, setIsVegetarian] = useState('')
      const [priceRange, setPriceRange] = useState('$')
      const [foodList, setFoodList] = useState([])
    
      // Get data from the DB and display it:
      useEffect(() => {
        let unmounted = false
        Axios.get("https://my-app.com/read")
          .then((response) => {
            if (!unmounted) {
              setFoodList(response.data)
            }
          })
          .catch(error => {
            console.log(error)
            return
          })
        return () => {
          unmounted = true
        }
      }, [foodList])
    
      return ( 
        <div > {
          foodList.length > 0 && foodList.map((val, key) => {
              return (
                // Display a table of data here
                ...
              )
            }
          } 
        </div>
       )
    }

SearchFilter.js component:

export default function SearchFilter(props) {
  const [searchedFood, setSearchedFood] = useState([])
  const [textSearch, setTextSearch] = useState('')
  const [priceDropdown, setPriceDropdown] = useState('')
  const [vegDropdown, setVegDropdown] = useState('')

 // The problem is in here:
  const newSearch = props.foodList.filter((value) => {
        return (
          value.foodName.toLowerCase().includes(textSearch.toLowerCase()) &&
          value.priceRange.toLowerCase().includes(priceDropdown.toLocaleLowerCase()) 
          && value.isVegetarian.includes(vegDropdown.toLowerCase())
        )
      }
  )

  const handleSearch = (event) => {
    event.preventDefault()
    if (textSearch !== '') {
      setSearchedFood(newSearch)
    }
  }

  const clearSearch = (event) => {
    event.preventDefault()
    setSearchedFood([])
    setTextSearch('')
    setPriceDropdown('')
    setVegDropdown('')
  }


  return (
    <section className="search">
      <form className="search__form">
        <div className="search__controls">
          <label htmlFor="text-search">Search a dish: </label>
          <input type="text" placeholder="Search food name" name="text-search" autoComplete="off" value={textSearch} onChange={(event) => {setTextSearch(event.target.value)
            console.log(event.target.value)
          }} />
        </div>
        <div className="search__controls">
          <label>Filter by price range: </label>
          <select value={priceDropdown} onChange={(event) => {setPriceDropdown(event.target.value)}} >
            <option value="">All</option>
            <option value="$">$</option>
            <option value="$$">$$</option>
            <option value="$$$">$$$</option>
          </select>
        </div>
        <div className="search__controls">
          <label htmlFor="veg-dropdown">Filter by vegetarian: </label>
          <select name="veg-dropdown" value={vegDropdown} onChange={(event) => {setVegDropdown(event.target.value)}} >
            <option value="">--</option>
            <option value="No">No</option>
            <option value="Yes">Yes</option>
          </select>
        </div>
        <button className="btn" onClick={handleSearch}><HiSearch /></button>
        <button className="btn" onClick={clearSearch}><MdClear /></button>
      </form>
      <div className="data-result">
        {searchedFood.map((value, key) => {
          return (
            <div key={key}>
              {value.isVegetarian === "yes" 
                ? <p>{value.foodName}{<FaSeedling className="i-veggie" />}</p>
                : <p>{value.foodName}</p>
              }
              <p>{value.priceRange}</p>
            </div>
          )
        })}
      </div>
    </section>
  );
}

‘ More Details ‘ button pushes aligned div content out of alignment

I have two rows of four div class thumbnails with a see more details button, which when pressed shows more text. When I was testing a single thumbnail it worked fine, but now with two rows of thumbnails. When the button is clicked, the other thumbnails are pushed out of the singly. I have tried to aligned these with inline block but this change made the ‘see more’ text hidden underneath the thumbnail as the next row doesn’t drop the content down.

On another page I have a <h2 in-between the thumbnail rows and this works perfectly but when the two rows are directly after each other they don’t react how it should. Either showing the text under the thumbnail or displacing the whole next row of thumbnails.

function toggle(button) {

  const moreDetailses = document.querySelectorAll(".moreDetails");
  for (let i = 0; i < moreDetailses.length; i++) {
    moreDetailses[i].style.display = "none";
  }
}
.thumbnail-row {
  height: 400px;
  width: auto;
}

.thumbnail-frame {
  width: 19.75%;
  height: auto;
  margin-left: 4%;
  float: left;
}

.thumbnail-frame a {
  margin: 0;
}

.thumbnail-frame h3 {
  text-align: center;
}

.thumbnail-frame h4 {
  text-align: center;
}

.thumbnail {
  background-color: black;
  width: 100%;
  height: 350px;
  display: inline-block;
  /* makes it fit in like an <img> */
  background-size: cover;
  /* or contain */
  background-position: center center;
  background-repeat: no-repeat;
}
<div class="thumbnail-row">
  <div class="thumbnail-frame">
    <div class="thumbnail" style="background-image: url(myharddrivedirctory);"></div>
    <div class="details">
      <div class="moreDetails">
        <h3> episode 01 details </h3>
      </div>
      <button title="Click to Show" type="button" onclick="toggle(this)">More Details</button>
    </div>
  </div>
  <div class="thumbnail-frame">
    <div class="thumbnail" style="background-image: url(myharddrivedirctory);"></div>
    <div class="details">
      <div class="moreDetails">
        <h3> episode 02 details </h3>
      </div>
      <button title="Click to Show" type="button" onclick="toggle(this)">More Details</button>
    </div>
  </div>
  <div class="thumbnail-frame">
    <div class="thumbnail" style="background-image: url(myharddrivedirctory);"></div>
    <div class="details">
      <div class="moreDetails">
        <h3> episode 03 details </h3>
      </div>
      <button title="Click to Show" type="button" onclick="toggle(this)">More Details</button>
    </div>
  </div>
  <div class="thumbnail-frame">
    <div class="thumbnail" style="background-image: url(myharddrivedirctory);"></div>
    <div class="details">
      <div class="moreDetails">
        <h3> episode 04 details </h3>
      </div>
      <button title="Click to Show" type="button" onclick="toggle(this)">More Details</button>
    </div>
  </div>
</div>

<div class="thumbnail-row">
  <div class="thumbnail-frame">
    <div class="thumbnail" style="background-image: url(myharddrivedirctory);"></div>
    <div class="details">
      <div class="moreDetails">
        <h3> episode 05 details </h3>
      </div>
      <button title="Click to Show" type="button" onclick="toggle(this)">More Details</button>
    </div>
  </div>
  <div class="thumbnail-frame">
    <div class="thumbnail" style="background-image: url(myharddrivedirctory);"></div>
    <div class="details">
      <div class="moreDetails">
        <h3> episode 06 details </h3>
      </div>
      <button title="Click to Show" type="button" onclick="toggle(this)">More Details</button>
    </div>
  </div>
</div>

JavaScript data attributes and dataset confusion

I am learning JavaScript and I saw a video about creating tabs using HTML, CSS, and JavaScript. But I am not understanding how the code is working. This is a codepen of the code: Tabs Codepen by WebDevSimplified. To be more specific I am not understanding what the value of target will be in this line const target = document.querySelector(tab.dataset.tabTarget);. Is it taking the values #home, #pricing and #about from data-tab-target and applying the class active on the specific data-tab-content based on which data-tab-target the user clicks on?

Angular Http POST request resulting in 500 error

I’m trying to make a post request to my webserver but only getting an internal server error. I’ve tested sending a post request to the server through a REST client, which works fine. What am I missing?

postCity(city: ICity, country: string): Observable<ICountry> {
    return this.http.post<ICountry>(this.url, city, {
      headers: new HttpHeaders({
          'Content-Type': 'application/x-www-form-urlencoded; charset=utf-8'
      })
    });
 }

React Native Firestore pagination issue

I’m working on a project using React-Native and the react-native-firebase librairy.

Within this project i’m trying to implement simple pagination with next and previous buttons.
I’m using startAfter() / limit() for the next one and endBefore() / limitTolast() for the previous one.

Here is my code

useEffect(() => {

        setCurrentPage(1)
        setViews([])
        setLoading(true)
        firestore()
        .collection('feed')
        .orderBy("creation", "desc")
        .limit(limit)
        .get()
        .then((snapshot) => {
                const data = snapshot.docs.map(doc => doc.data())
                const lastVisibleDoc = snapshot.docs[snapshot.docs.length - 1]
                const firstVisibleDoc = snapshot.docs[0]
                setViews(data)
                setLastVisible(lastVisibleDoc)
                setFirstVisible(firstVisibleDoc)
                setLoading(false)
        })
    }, [currentUserPreference])

This one part will get the first shot of data and works just fine.

const nextPage = () => {

        setCurrentPage(currentPage + 1)
      
          setLoading(true)
          scrollRef?.current?.scrollTo({y: 0, animated: true})
            firestore()
            .collection('feed')
            .orderBy("creation", "desc")
            .startAfter(lastVisible)
            .limit(limit)
            .get()
            .then((snapshot) => {
              const data = snapshot.docs.map((doc) => doc.data())
              const lastVisibleDoc = snapshot.docs[snapshot.docs.length - 1]
              const firstVisibleDoc = snapshot.docs[0]
              setViews(data)
              setLastVisible(lastVisibleDoc)
              setFirstVisible(firstVisibleDoc)
              console.log('fv', firstVisibleDoc)
          })
          console.log("more")
          setLoading(false)

This one is to get the next docs works as it should as well.

const lastPage = () => {

      setCurrentPage(currentPage - 1)
      
        setLoading(true)
        scrollRef?.current?.scrollTo({y: 0, animated: true})
        firestore()
        .collection('feed')
        .orderBy("creation", "desc")
        .endBefore(firstVisible)  
        .limitToLast(limit)
        .get()
        .then((snapshot) => {
          const data = snapshot.docs.map((doc) => doc.data())
          const lastVisibleDoc = snapshot.docs[snapshot.docs.length - 1]
          const firstVisibleDoc = snapshot.docs[0]
          console.log('ld', data)
          console.log('lvlp', lastVisibleDoc)
          console.log('lvlp', firstVisibleDoc)
          setViews(data)
          setLastVisible(lastVisibleDoc)        
          setFirstVisible(firstVisibleDoc)   
      })
      console.log("less")
      setLoading(false)

This is where the issue is located. My request seems to be off at some point because it doesn’t return me anything it doesn’t reach ‘then’ either as my state values doesn’t get updated and i don’t get the logs i placed in there.
It doesn’t give me any warnings or errors. As i keep track of the current page within a state it gets updated but that’s the only thing. Other than that nothing, it stays on the same page with the previous data displayed.

I don’t know where is the mistake, if you have any idea, i will take it.

Thanks for your help !

Data is capturing incomplete when submit by different user at a time

Created HTML form but when submit the form ata time by two defferent users its capturing incomplete data like few data showing as blank in first submit and second submit its caprturing all the informations. Need you assitence how to prevent this issues.

<script>
  // Prevent forms from submitting.
  function preventFormSubmit() {
    var forms = document.querySelectorAll('form');
    for (var i = 0; i < forms.length; i++) {
      forms[i].addEventListener('submit', function(event) {
      event.preventDefault();
      });
    }
  }
  window.addEventListener('load', preventFormSubmit);    
     
     
  function handleFormSubmit(formObject) {
 google.script.run.processForm(formObject);
 
     
   }
 
 
 
 
</script>

Reactjs Debugging On Development Environment [closed]

am using reactjs current version. I created my application using npx create-react-app appname. I have a scenario where the application doesn’t render component. From the ide am using which is visual studio code no error highlited and the same sametime can’t view any error from chrome developer console to help me debug the application. Anyone who knows how to go about such a case.

HTML Background Missing After Site Migration

I made a powerpoint presentation & converted it to HTML at https://www.idrsolutions.com/online-powerpoint-to-html5-converter
The output html page on the mentioned site looks perfect for me.
But after I downloaded zip and put the contents on my new site (Ubuntu & PHP7 fresh install) I don’t see the blue background.
My site is https://castaneda.su/DK/221023
I tried to make these steps for my another site https://alpin52.ru/221023 (preconfigured by host provider) and the look is as required.
I think the problem is that I missed installing some component on the server. But I cannot figure out which. Thanks.

can’t use clearInterval

in trying to create a page that will show the current time which will refresh every x seconds – x is a user input
i use setInterval and clearInterval but it looks like the clearInterval doesn’t have any effect at all 🙁
here’s the code:

 <script>
      let changeTime = () => {
        let secs = document.getElementById("sec").value * 1000;
        clearInterval(timer);
        let timer = setInterval(() => {
          let d = new Date();
          document.getElementById("example").innerHTML = d.toLocaleString();
          console.log(secs);
        }, secs);
      };

      function clear() {
        clearInterval(timer);
      }

      //both functions are called with an onChange event

thanks!

Accept Declaimer after click on button

   <input type="checkbox"   id="confirm"> I have read and agree to this disclaimer as well as 
   <p class="d-none text-danger">Please read and agree to this disclaimer 
   above.</p>
   
   <button type="button" class="close" >Continue</button>

if does not checked checkbox then click on button the get error of p text and if checked the
checkbox then click on button then close popup