Trying to make scroll buttons work on their corrispective containers

I’m trying to make 2 buttons for a scroll left and scroll right while working on a Netflix copy, as you can imagine i’m just learning. I’m working on my project with VueJs, i made my btns work but they only work on the movie list while the rest of the btn does nothing, i’m missing something for sure but i still didn’t find a solution:

<Template>
<!-- this is our film container -->
    <div id="movieCards" class="container pt-5 pb-5" v-if="store.movie.length > 0">
            <div>
                <h2>
                    Film
                </h2>
            </div>
            <div ref="movieScrollContainer" class="dflex">
                <div class="ls-col" v-for="movie in store.movie" :key="movie.id">
                    <CardComponent :img="store.ImageUrl + movie.poster_path" :name="movie.title" :originalName="movie.original_title" :language="movie.original_language" :vote="movie.vote_average" :overview="movie.overview"/>
                </div>
            </div>
            <div class="d-flex justify-content-between ">

                <button id="scrollLeftMovie" @click="scroll(-600, 'movieScrollContainer')">
                 scroll left
                </button>

                <button id="scrollRightMovie" @click="scroll(600, 'movieScrollContainer')">
                 scroll right
                </button>
            </div>
    </div>
    <!-- this is our tvseries container -->
    <div ref="tvScrollContainer" id="tvCards" class="container pt-5 pb-5" v-if="store.movie.length > 0">
            <div>
                <h2>
                    Serie TV
                </h2>
            </div>
        <div class="dflex">
            <div class="ls-col" v-for="series in store.tv" :key="series.id">
                <CardComponent :img="store.ImageUrl + series.poster_path" :name="series.name" :originalName="series.original_name" :language="series.original_language" :vote="series.vote_average" :overview="series.overview"/>
            </div>
        </div>

        <div class="d-flex justify-content-between">
            <button id="scrollLeftTv" @click="scroll(-600, 'tvScrollContainer')">
                scroll left
            </button>

            <button id="scrollRightTv" @click="scroll(600, 'tvScrollContainer')">
                scroll right
            </button>
        </div>

    </div>
</Template>

i triyed to give a 2nd parameter to the function but it seems i’m doing it wrong. Function here:

<script>
import { store } from '../store';
import CardComponent from './CardComponent.vue';
    export default {
        name: 'CardList',
        components: {
            CardComponent
        },
        data() {
            return {
                store
            }
        },
        methods: {
           scroll(distance, id) {
            this.$refs[id].scrollBy({
                left: distance,
                behavior: 'smooth'
            })
           }
        }
    }
</script>

Can someone help me understand what is missing?

Paypal capturing payment issue. COMPLIANCE_VIOLATION. The requested action could not be performed semantically incorrect or failed business validation

Im trying to add PayPal payments to my site. Im using official @paypal/paypal-js npm package and Nuxt 2.16.

What I expected: Im creating an order at my db on my backend, then creating paypal order and rendering paypal buttons on client side.
I expect to continue processing our clients order when paypal hits our webhook on client site with event_type: “PAYMENT.CAPTURE.COMPLETED”

Issue: When I was using sandbox_business and sandbox_personal accounts everything worked just fine.
But when I switched to production credentials its not working. Now onError callback is triggering. Funds are withdrawn from the user, and returned after a few seconds.

Here is an Error at paypal dashboard (Error screenshot):

status: 422

issue: COMPLIANCE_VIOLATION

description: The requested action could not be performed semantically incorrect or failed business validation

Here is my client code:

<template>
    <div>
        <div id="paypal-button-container"></div>
    </div>
</template>

<script>

import { loadScript } from '@paypal/paypal-js';

export default {
    methods: {
        async createOrder() {
              await this.$axios.$post("/api/pay", order).then(async (result) =>{
                    if (result.error) {
                        //some error hadling
                    } else {
                            const paypal = await loadScript({
                            'client-id': "MY_CLIENT_ID",
                            currency: "EUR",
                            intent: "capture",
                        });

                        await paypal.Buttons({
                            createOrder: function(data, actions) {
                                return actions.order.create({
                                    purchase_units: [{
                                        amount: {
                                            currency_code: 'EUR',
                                            value: result.price,
                                        },
                                        description: result.order_description,
                                        reference_id: result.order_id,
                                    }],
                                    intent: 'CAPTURE'
                                });
                            },  

                            onApprove: (data, actions) => {
                                return actions.order.capture().then((orderData, action) => {
                                    this.$router.push("/payment/success");
                                })
                            },

                            onError: (err) => {
                                console.log(err);
                            },
                        }).render('#paypal-button-container');

                    }
              }

        },

    },

I tried to pass different values to createOrder function. But couldnt figure out what was the problem.

Also i logged out err from onError callback, but it returned just empty object {}.

No routes matched location “/” and searchbar, pagination and filter not displaying. React.js

When i added the searchbar logic, the pagination and the filter, I got the error “No routes matched location “/””. I’m using Postman to test if the logic is right and it works, but for some reason the elements aren’t displaying. I think the error might be in the routing but it looks fine to me.

App.js where the routing is:

import Login from './components/user/Login';

const alertOptions = {
  position: positions.BOTTOM_CENTER,
  timeout: 5000,
  offset: '30px',
  transition: transitions.SCALE
};

function App() {
  return (
    <AlertProvider template={AlertTemplate} {...alertOptions}>
      <Router>
        <div className="App">
          <Header />
          <div className="container container-fluid">
            <Routes>
              <Route path="/" element={<Home />} exact />
              <Route path="/search/:keyword" element={<Home />} />
              <Route path="/product/:id" element={<ProductDetails />} exact />
              <Route path="/login" element={<Login />} />
            </Routes>
          </div>
          <Footer />
        </div>
      </Router>
    </AlertProvider>
  );
}

export default App;

Home.js component where the filter and pagination are supposed to be displayed:

import React, { Fragment, useState, useEffect } from "react";
import { useParams } from "react-router-dom";
import Pagination from "react-js-pagination";
import Slider from "rc-slider";
import "rc-slider/assets/index.css";
import MetaData from "./layout/MetaData";
import Product from "./product/Product";
import Loader from "./layout/Loader";
import { useDispatch, useSelector } from "react-redux";
import { getProducts } from "../actions/productActions";

const Home = () => {
  const [currentPage, setCurrentPage] = useState(1);
  const [price, setPrice] = useState([0, 1000]);
  const { keyword } = useParams();
  const dispatch = useDispatch();
  const { loading, products, error, productsCount, resPerPage } = useSelector(
    (state) => state.products
  );

  useEffect(() => {
    if (error) {
      return alert.error(error);
    }

    dispatch(getProducts(keyword, currentPage, price));
  }, [dispatch, error, keyword, currentPage, price]);

  function setCurrentPageNo(pageNumber) {
    setCurrentPage(pageNumber);
  }

  return (
    <Fragment>
      {loading ? (
        <Loader />
      ) : (
        <Fragment>
          <MetaData title={"Buy the best plugins for FL Studio!"} />
          <h1 id="products-heading"></h1>
          <section id="products" className="container mt-5">
            <div className="row">
              {keyword ? (
                <Fragment>
                  <div className="col-6 col-md-3 mt-5 mb-5">
                    <div className="px-5">
                      {}
                      <Slider.Range
                        marks={{
                          0: "0",
                          1000: "1000",
                        }}
                        min={0}
                        max={1000}
                        defaultValue={[0, 1000]}
                        tipFormater={(value) => value}
                        tipProps={{
                          placement: "top",
                          visible: true,
                        }}
                        value={price}
                        onChange={(price) => setPrice(price)}
                      />
                    </div>
                  </div>
                  <div className="col-6 col-md-9">
                    <div className="row">
                      {products.map((product) => (
                        <Product key={product._id} product={product} col={4}/>
                      ))}
                    </div>
                  </div>
                </Fragment>
              ) : (
                products.map((product) => (
                  <Product key={product._id} product={product} col={3}/>
                ))
              )}
            </div>
          </section>
          {resPerPage <= currentPage && (
            <div className="d-flex justify-content-center mt-5">
              <Pagination
                activePage={currentPage}
                itemsCountPerPage={resPerPage}
                totalItemsCount={productsCount}
                onChange={setCurrentPageNo}
                nextPageText={"Next"}
                prevPageText={"Previous"}
                firstPageText={"First"}
                lastPageText={"Last"}
                itemClass="page-item"
                linkClass="page-link"
              />
            </div>
          )}
        </Fragment>
      )}
    </Fragment>
  );
};

export default Home;

getProducts from productActions.js:

export const getProducts = (keyword = '',currentPage = 1, price) => async (dispatch) => {
    try {
        dispatch({ type: ALL_PRODUCTS_REQUEST });

        let link = `/api/v1/products?keyword=${keyword}&page=${currentPage}&price[lte]=${price[1]}&price[gte]=${price[0]}`
        const {data} = await axios.get(link);

        dispatch({
            type: ALL_PRODUCTS_SUCCESS,
            payload: data
        });
    } catch (error) {
        dispatch({
            type: ALL_PRODUCTS_FAIL,
            payload: error.response.data.message
        });
    }
};

Search.js for the searchbar:

import React, {useState} from 'react'

const Search = ({history}) => {
    const [keyword, setKeyword] = useState('')
    const searchHandler = (e) => {
        e.preventDefault();
        
        if(keyword.trim()){
            history.pushState(`/search/${keyword}`)
        } else {
            history.pushState('/')
        }
    }

  return (
    <form onSubmit={searchHandler}>
      <div className="input-group">
            <input
              type="text"
              id="search_field"
              className="form-control"
              placeholder="Пакети, инструментали, плъгини..."
              onChange={(e) => setKeyword(e.target.value)}
            />
            <div className="input-group-append">
              <button id="search_btn" className="btn">
                <i className="fa fa-search" aria-hidden="true"></i>
              </button>
            </div>
          </div>
    </form>
  )
}
export default Search

And Header.js where the searchbar is:

import React, { Fragment } from "react";
import Search from './Search';
import { Link , Routes, Route} from "react-router-dom";
import "../../App.css";

const Header = ({product}) => {
  return (
    <Fragment>
      <nav className="navbar row">
        <div className="col-12 col-md-3">
          <Link to={'/'}>
            <div className="navbar-brand">
              <img
                src="/images/Logo.png"
                style={{ width: "100px", height: "100px" }}
                alt=""
              />
            </div>
          </Link>
        </div>

        <div className="col-12 col-md-6 mt-2 mt-md-0">
        <Routes>
            <Route render={({history}) => <Search history={history} />} />
        </Routes>
        </div>

        <div className="col-12 col-md-3 mt-4 mt-md-0 text-center">
          <Link to="/login" className="btn ml-4" id="login_btn">
            Регистрация
          </Link>
          <span id="cart" className="ml-3">
            Количка
          </span>
          <span className="ml-1" id="cart_count">
            2
          </span>
        </div>
      </nav>
    </Fragment>
  );
};

export default Header;

I hope this code is enough. Thank you in advance!

Can you add to multiple array variables at once? [closed]

I have been coding recently and I can into a problem with arrays, adding to them took too long. So, I was wondering if there was anyway to add to multiple variables in an array in one line of code. Here is what I was doing

const array = [0, 0, 0]

array[0]++
array[1]++
array[2]++

Is there any way to put this into a single line of code?

Get system icons for folders and files without an extension in Electron

I am trying to display some contents of a folder in my Electron app, and am fetching the system icons of each file/folder with app.getFileIcon(filePath). However, icons for folders and for files that are missing an extension are not found (it returns [Error: Failed to get file icon.]. I haven’t been able to find anything online about how to get these icons.

If anyone knows how I can get the system icons for all folders and types of files, it would be greatly appreciated. I am using Ubuntu.

Thanks!

Why am i getting this error while trying to start my IC server

I am trying to start my internet computer server, but while running “npm start” command i am getting the following error. Why is that happening?

> [email protected] prestart
> npm run copy:types


> [email protected] copy:types
> rsync -avr .dfx/$(echo ${DFX_NETWORK:-'**'})/canisters/** --exclude='assets/' --exclude='idl/' --exclude='*.wasm' --exclude='*.most' --delete src/declarations

sending incremental file list
name_assets/

sent 336 bytes  received 17 bytes  706.00 bytes/sec
total size is 19,098  speedup is 54.10

> [email protected] start
> webpack serve --mode development --env development

No production canister_ids.json found. Continuing with local
[webpack-cli] TypeError: cli.isMultipleCompiler is not a function
    at Command.<anonymous> (/home/sree/ic-project/name/node_modules/@webpack-cli/serve/lib/index.js:146:35)
    at async Promise.all (index 1)
    at async Command.<anonymous> (/home/sree/ic-project/name/node_modules/webpack-cli/lib/webpack-cli.js:1672:7)

I want to get rid of this error. What changes should i make inorder to properly start my server

Build a math equation renderer [closed]

I want to build a math equation renderer like Katex, but I don’t know where to start. I can’t find any tutorial to get started, no name of the algorithms to do it, nor the standards for defining the size and position of the characters. All the libraries available on Github do not say how they do this.

I searched the internet for solutions but couldn’t find anything.

Map container already initialized in LeafletJS when using printThis

I’m using printThis to print a bunch of elements from a page in an application.

I’m encountering the following error:

leaflet.js:5 Uncaught Error: Map container is already initialized.
at e._initContainer (leaflet.js:5:31752)
at e.initialize (leaflet.js:5:20608)
at new e (leaflet.js:5:2745)
at o.map (leaflet.js:6:8323)
at initLeafletMap (JsCombinerV22023702496814.ashx?jsLocal=true:57688:22)
at StatisticMapControl.LoadLeafletMap (JsCombinerV22023702496814.ashx?jsLocal=true:57375:24)
at eval (eval at <anonymous> (jquery.min.js:2:14136), <anonymous>:2:36)
at eval (<anonymous>)
at jquery.min.js:2:14136
at Function.globalEval (jquery.min.js:2:14147)

But this only happens the first time I click “print” when loading the application page. If, once loaded, I navigate through different menus and try to print in those menus, I don’t have any errors. If I come back to the default page, I don’t get any errors as well.

The error happens in the leaflet file (from the library)

_initContainer: function(t) {
            var e = this._container = o.DomUtil.get(t);
            if (!e)
                throw new Error("Map container not found.");
            if (e._leaflet_id)
                throw new Error("Map container is already initialized.");
            o.DomEvent.addListener(e, "scroll", this._onScroll, this),
            this._containerId = o.Util.stamp(e)
        },

when I invoke it:

function initLeafletMap(mapContainerId) {
return L.map(mapContainerId, { zoomControl: false, tap: false, zoomSnap: 0 });
};

After invoking it, part of the code that runs inside leaflet is this:

o.Class.extend = function(t) {
var e = function() {
this.initialize && this.initialize.apply(this, arguments),
this.callInitHooks()
}

It seems that initialize is called twice, which in turn calls initContainer, where the exception occurs that the map container has already been initialized.

Should I modify something in that function so that initialize is only called once? I wouldn’t want to modify an external library.

I’ve researched, and in many places, they suggest setting the map to null before invoking the function. In my case, this is already done just before invoking the map:

this.map = null;
this.map = initLeafletMap(mapContainerId);

Before using printThis, something else was used (I’m not sure what) to grab the desired elements from the page and form a document for printing. Leaflet.js was also used and did not cause any problems.

If anyone knows what the problem might be or what I can try, I would appreciate it.

How to integrate custom bulid CKEditor 5 in my Vue App

I have made a custom build from CKEditor 5 Online Builder and Downloaded it but It is build in Webpack and I’m using Vite in Vue 3 Project.

I have tried below code:

<script setup>
import CKEditor from "@/ckeditor5-custom-build/build/ckeditor"
import { component as ckeditor } from "@ckeditor/ckeditor5-vue";

const editor = ref(CKEditor);
const editorData = ref("");
const editorConfig = ref({});
</script>

<template>
    <ckeditor :editor="editor" :config="editorConfig" v-model="editorData"></ckeditor>
</template>

I’m getting below error:

Module not found: Error: Can’t resolve ‘ckeditor5-custom-build/build/ckeditor’

react bootstrap table error:- Cannot read properties of undefined (reading ‘id’) at Function.get (react-bootstrap-table-next.js?v=52eb8e95:1478:29)

I am implementing the react bootstrap table , I have 2 component 1 is for search input and other is for showing fetch data in table, I have implmented the serach and bootstrap pagination as below
** Search.tsx file **

    const [filterForm, setFilterForm] = useState<FilterForm>({
        id: null,
        location: "",
        name: "",
        pageSize: "10",
        pageNo: "1",
        userData: userData,
      });
  const [tableData, setTableData] = useState<UserInquiry[]>([]);

const handleFindPagination = async (pageNumber: string, pageSize:string) => {
    try {
      
      setLoading(true);
    let FETCH_DATA = {...filterForm,
      pageNo: pageNumber,
      pageSize: pageSize,
    };
    fetchData(FETCH_DATA);
  } catch (error) {
    console.error("Error in handleFindPagination:", error);
  }finally{
    setLoading(false);
  }
  };
const fetchData = async (data: FilterForm) => {
    let FETCH_DATA = {};
    addLoadingTask(FETCH_DATA);
    try {
     
      const result = await UserInquiryService.searchUserInquiryList(data); //API call

    console.log(result);
      const resultContent = result.data.resultContent;
      if (result) {
        if(result.data.resultStatus !="F" )
        {
          setTableData(resultContent);
          setLastCount( parseInt(resultContent[0].lastCount));
        }else{
          if (resultContent.length == 0) {
            addAlertNotification({
              status: "ERROR",
              message: "*Data Not Found",
            });

          }
        }
      }
      console.log(resultContent);
    } catch (error) {
      console.error("Error fetching data:", error);
    } finally {
      removeLoadingTask(FETCH_DATA);
    }
  };
const handleFind= async () => {
    fetchData(filterForm);
  };
return (
    <>
//search field related inputtext <div's> like id,location,name etc. not passing to save some spave
   <div className="mt-3 d-flex justify-content-end align-items-center">
            <Button
              customClassName="mr-1"
              variant="find"
              onClick={() => {
                handleFind();
              }}
            />
          </div>
    <UserInquiryTable
        filteredData={tableData}
        lastCount={lastCount}//total row count 
        userData={userData}
        onPaginationChange={handleFindPagination}
      />

** UserTable.tsx file **

const UserInquiryTable: React.FC<UserInquirySearchProps> = ({
  filteredData,
  lastCount,
  userData,
  onPaginationChange
}) => {



const handlePaginationChange = (pageNo: number, pageSize: number) => {
    onPaginationChange(pageNo.toString(), pageSize.toString());
  };

const paginationOptions = {
    custom: true,
    paginationSize: 5,
    pageStartIndex: 1,
    showTotal: true,
    totalSize: lastCount,
    disablePageTitle: true,
    sizePerPageList: [
      {
        text: "10",
        value: 10,
      },
      {
        text: "20",
        value: 20,
      },
      {
        text: "30",
        value: 30,
      },
      {
        text: "100",
        value: 100,
      },
    ],
    onPageChange: (newPage:number, newSizePerPage:number) => handlePaginationChange(newPage,newSizePerPage),
  };
 return (
    <div className="container-fluid">
      <div className="mt-4">
        <CardCollapsable
          title={"Search Result"}
          actionChildren={actionChildren}
          initialExpanded={true}
        >
          <Card.Body>
            <PaginationProvider
              pagination={paginationFactory(paginationOptions)}
            >
              {({ paginationProps, paginationTableProps }) => {
                return (
                  <div>
                    <div className="my-1" style={{ fontSize: "13px" }}>
                      Show{" "}
                      <SizePerPageDropdownStandalone
                        {...paginationProps}
                        btnContextual={"btn-outline-secondary" as any}
                      />{" "}
                      entries
                    </div>
                    <BootstrapTable
                      bootstrap4
                      striped
                      wrapperClasses="table-responsive"
                      {...paginationTableProps}
                      keyField="id"
                      data={filteredData}
                      columns={columns}
                      defaultSortDirection="asc"
                      defaultSorted={[
                        {
                          dataField: "module",
                          order: "asc",
                        },
                      ]}
                    />
                    <div
                      className="mx-1 row"
                      style={{
                        display: "flex",
                        justifyContent: "space-between",
                      }}
                    >
                      <PaginationTotalStandalone {...paginationProps} />
                      <PaginationListStandalone {...paginationProps} />
                    </div>
                  </div>
                );
              }}
            </PaginationProvider>
           
          </Card.Body>
        </CardCollapsable>
      </div>
    </div>
  );

};

so issue here, when I click on find button I am able to get the records but when I try to select anaother page to make API call, page turn white and got error

Uncaught TypeError: Cannot read properties of undefined (reading ‘id’)
at Function.get (react-bootstrap-table-next.js?v=52eb8e95:1478:29)
at react-bootstrap-table-next.js?v=52eb8e95:5627:41

I am not sure , but not getting what step I am doing wrong here, Please help , Thanks in adanvce

Cannot read properties of undefined (reading ‘filter’) in ReactJS

I have problem when I try to filter a list by name of products that are shown on website

File filterSlice

import { createSlice } from '@reduxjs/toolkit'

const initialState = {
    filtered: []
}

const filterSlice = createSlice({
  name: "filter",
  initialState,
  reducers: {
    
    FILTER_PRODUCTS(state, action){
        const {products, search} = action.payload;
**        const tempProduct = products.filter(
**          (product =>
          product.name.toLowerCase().includes(search.toLowerCase())
        ));
        state.filtered = tempProduct;
    },
  }
});

export const {FILTER_PRODUCTS} = filterSlice.actions;

export const selectFiltered = (state) => state.filter.filtered;


export default filterSlice.reducer;

File ProductList, that I added filter funcion into

const ProductList = ({products, isLoading}) => {

  const [search, setSearch] = useState("")
  const filterProduct = useSelector(selectFiltered)

  ...

  useEffect(() => {
    dispatch(FILTER_PRODUCTS(products, search))
  }, [products, search, dispatch])

  return (
    <div className='product-list'>
      <hr />
      <div className='table'>
        ...

        {isLoading}
        <div className='table'>
**        { !isLoading && filterProduct.length === 0 ? (
**            <p>No product found</p>          
            ) : (
            <table>
              <thead>
                   ...
              </thead>
              <tbody>
                {
                  //Show array of all products in screen
**                  filterProduct.map((product) => {
**                    const {_id, name, category, inventorynumber, 
                      serialnumber, guarantee, price} = product;
                    return (
                      <tr key={_id}>
                         ...
                      </tr>

There are 3 important lines in 2 files

{ !isLoading && filterProduct.length === 0 ? (

filterProduct.map((product) => {

const tempProduct = products.filter(

products is a list that I added some items, so it’s defined and has contents inside.

But it always recognized that it’s undefined and it shows error “Cannot read properties of undefined (reading ‘filter’)”

A solution I tried was addition of ? after variants:

filterProduct?.length

filterProduct?.map

products?.filter

The error disappears but website doesn’t show any items. But it’s weird because I expected it shows all item after filtered.
I think I can’t use ? in this situation. Does anyone know how to solve it? Thanks in advance.

WeakRef and garbage collection don’t work as expected

In my project I found myself in need of using WeakRefs and FinalizationRegistry, but I can’t quite manage to make it work, so I created a simple example and it also does not work. Can you help me figure out why the simple example does not work:

Example code:

    let ref = new WeakRef({});

    console.log("log", ref, ref.deref());

    global.gc();

    new Promise((res)=>{
        setTimeout(()=>{res()}, 100_000)
    }).then(()=>{
        console.log("log2", ref, ref.deref());
    })

    global.gc();

    console.log("log3", ref, ref.deref());

expected output:

log WeakRef {} {}

log3 WeakRef {} undefined // maybe here still log3 WeakRef {} {}

log2 WeakRef {} undefined // here for sure!!!

Real output:

log WeakRef {} {}

log3 WeakRef {} {}

log2 WeakRef {} {}

alternative without “forcing” garbage collection with global.gc() also yielded the result above.

command I used to run examples:
node --expose-gc {filename}.js in case of the code above or
node {filename}.js when running tests without global.gc()

node versions I tried:
17.9.1
20.10.0
21.7.3

Sorting array of flight offers based on price total and retrieving first five results – Angular HTTP request

I send an API request and get:

Object { meta: {…}, data: (75) […], dictionaries: {…} }
​
data: Array(75) [ {…}, {…}, {…}, … ]
​​
0: Object { type: "flight-offer", id: "1", source: "GDS", … }
​​
1: Object { type: "flight-offer", id: "2", source: "GDS", … }
​​
2: Object { type: "flight-offer", id: "3", source: "GDS", … }
​​
3: Object { type: "flight-offer", id: "4", source: "GDS", … }
​​
4: Object { type: "flight-offer", id: "5", source: "GDS", … }
​​
5: Object { type: "flight-offer", id: "6", source: "GDS", … }
​​
6: Object { type: "flight-offer", id: "7", source: "GDS", … }
​​
7: Object { type: "flight-offer", id: "8", source: "GDS", … }
​​
8: Object { type: "flight-offer", id: "9", source: "GDS", … }
​​
9: Object { type: "flight-offer", id: "10", source: "GDS", … }
​​
10: Object { type: "flight-offer", id: "11", source: "GDS", … }
​​
11: Object { type: "flight-offer", id: "12", source: "GDS", … }
​​
12: Object { type: "flight-offer", id: "13", source: "GDS", … }
​​
13: Object { type: "flight-offer", id: "14", source: "GDS", … }

and every single object looks like:

0: Object { type: "flight-offer", id: "1", source: "GDS", … }
​​​
id: "1"
​​​
instantTicketingRequired: false
​​​
itineraries: Array [ {…} ]
​​​
lastTicketingDate: "2024-04-20"
​​​
lastTicketingDateTime: "2024-04-20"
​​​
nonHomogeneous: false
​​​
numberOfBookableSeats: 9
​​​
oneWay: false
​​​
price: Object { currency: "EUR", total: "580.13", base: "257.00", … }
​​​
pricingOptions: Object { fareType: (1) […], includedCheckedBagsOnly: true }
​​​
source: "GDS"
​​​
travelerPricings: Array [ {…} ]
​​​
type: "flight-offer"
​​​
validatingAirlineCodes: Array [ "TK" ]

and i want to sort the results based on the price. So i have an array of all this objects based on the price, and then i would like to get first 5 results.

i tried:

this.http.get(url, { headers: this.headers }).subscribe((data: any) => {
      this.responseData$ = data;
      console.log(data);
      const flightOffers = data.data || []; // Assuming flight offers are in `data.data`

      // Sort the flight offers by price.total
      let sortedResults: any[] = flightOffers.sort(
        (offerA: any, offerB: any) => {
          // Ensure both offers have a price object and total property
          if (
            !offerA.price ||
            !offerA.price.total ||
            !offerB.price ||
            !offerB.price.total
          ) {
            console.warn(
              'One or more offers lack a valid price object or total property.',
            );
            return 0; // Maintain original order in case of missing prices
          }

          return offerA.price.total - offerB.price.total;
        },
      );

and

this.http.get(url, { headers: this.headers }).subscribe((data: any) => {
      this.responseData$ = data;
      console.log(data);
      let sortedResults = [];
      if (Array.isArray(data.data)) {
        sortedResults = data.data.sort((a, b) => {
          return parseFloat(a.price.total) - parseFloat(b.price.total);
        });
      }
      const firstFiveResults = sortedResults.slice(0, 5);

but it didnt work, and i get the array with 5 elements with the same price: total. How to sort it?