Looking to extract and multiply only the items at the even indexes of the array by the last item in the array

I'm troubleshooting this JavaScript code snippet:

const evenLast = arr => {
  return arr.filter((a,idx) => {
   if(!(idx&1)) return (a * arr[arr.length-1])
  })
}

console.log(evenLast([2, 3, 4, 5]))

When I run the code, it returns [2,4] instead of [10, 20]. I'm curious why the condition

if(!(idx&1)) return (a * arr[arr.length-1])
is resulting in only (a) rather than multiplying by last_item_of_array.

Answer №1

When working with arrays in JavaScript, two key methods to utilize are Array.filter and Array.map. While filter reduces an array to a smaller subset based on specified conditions, map is used to return a new array with the results of applying a function to each element. By combining these two methods effectively, you can achieve powerful manipulations of your data.

const evenRow = (_, idx) => {
  return idx&1;
};

const calculate = (val, _, arr) => {
  return val * arr.at(-1);
};

const evenLast = arr => {

  return arr.filter( evenRow ).map( calculate );

};

console.log( evenLast([2, 3, 4, 5]) );

Answer №2

To solve this issue, you can use the following code snippet:

function customFilter(arr){
    return arr.reduce((result, element, index) => {
        if(index % 2 === 0){
            result.push(element * arr[arr.length - 1]);
        }
        return result;
    }, []);
}

The problem occurred because when using filter, it evaluates the callback's result to determine whether to include the current item or not. In your case, the condition in the if statement always evaluated to true for all indices (except for an edge case where the item at that index is zero). This caused all items to be included instead of achieving the intended logic.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the process for transferring a file to a server from a PhoneGap or web application using FTP?

Can a PhoneGap application establish a connection with a server and transfer files using FTP? In simpler terms, is it feasible to initiate an FTP connection using Ajax or jQuery? ...

Tips for seamlessly integrating an overlay into a different image

My current system is set up to overlay the image when you check the checkboxes. However, I'm facing an issue with positioning the image inside the computer screen so it's not right at the edge. Can anyone provide assistance with this? <html&g ...

Ways to personalize the onSubmit function within tinacms

Having an issue with my Tina project. I am trying to develop my own submit button in Tinacms project, rather than using the sidebar or top bar provided by tinacms. I want to customize a button for onSubmit functionality. Any suggestions on how to achieve ...

JavaScript - splitting numbers into multiple parts

Need help with a JavaScript question regarding numbers like 2,5 or 2.5 I attempted to perform a multi-split operation using the following code: '2.5'.split(/,|./) However, it resulted in an incorrect output: ["", "", "", ""] ...

When the dependency value transitions from 1 to 0, useEffect fails to trigger

I'm really puzzled by how useEffect behaves in this scenario: Check out this code snippet: const numVertices = selectionProvider.verticesSelectionProvider.count; console.log('RENDER ---> COUNT = ', numVertices); useEffect(() => { ...

How to display only a portion of content using UI Bootstrap collapse feature

In my Angular.js application, I currently have a row of buttons that open up new routes to display partial views. Now, I need to modify some of these buttons to trigger a ui.bootstrap Collapse feature with the view inside it. The template code from the ui. ...

Guide on retrieving data from an axios promise in JavaScript

I am struggling to manage the output of multiple lists retrieved through an axios API call made in JavaScript. I want to know how to effectively log the results and save them for future use, particularly for creating a data visualization. Here is my curre ...

Trying out the Angular resolve feature

I am utilizing Angular with ui-router, so the toResolve variable will be resolved in my SomeController. .state('some.state', { url: '/some', controller: 'SomeController', templateUrl: '/static/views/som ...

Retrieve all entries in MongoDB using Mongoose where a particular date falls within a specified date range

Consider a scenario where documents contain the fields: startDate: 2021-04-14T22:00:00.000+00:00 endDate: 2021-04-19T22:00:00.000+00:00 You want to retrieve all documents where a specific date (e.g., today) falls within the date range. Is it possible to c ...

Passing information from the created hook to the mounted hook in VueJS

How can I transfer data from the created function to the mounted function in VueJS? In my VueJS application, the code in my created function is as follows: created: function(){ $.getJSON({ url: 'static/timeline.json', success:function( ...

Javascript floating navigation toolbar

How can I create a minimalist launch bar with a search button that only appears on a page when a specific hotkey is pressed? I want to avoid using large libraries like mootools or FancyBox for this Chrome Extension project to keep it lightweight. Do you ...

What is the process for assigning a regular expression to an object?

As I work on editing a configuration file, I'm encountering some issues where things aren't quite functioning as expected. Below is the code snippet I am working with: config.module.rules.unshift( { test: "/ckeditor5-[^/\\ ...

identify the row preceding the expiration month of a domain using JavaScript or jQuery

Is there a way to highlight the row representing the domain whose expiry month is before the current month, using the date and time information provided in the table (<td>2017-04-14 17:21:00</td>) with JavaScript or jQuery? <table> & ...

What is the process for logging data to a file in AngularJS?

I have a question regarding writing logs in an AngularJS project. Which logging method should I use to write logs to a file? Should I use Angular's $log or log4javascript? I currently have the following code configuration for using Angular's $log ...

JavaScript Fullcalendar script - converting the names of months and days

I recently integrated the Fullcalendar script into my website (https://fullcalendar.io/). Most of the features are functioning correctly, however, I am seeking to translate the English names of months and days of the week. Within the downloaded package, ...

Setting up a parameter to customize the Ajax function when a link is clicked

As I try to create a function for making an Ajax call, I find myself struggling to comprehend the execution of the onclick event. The goal is to fetch fields from a database via Ajax and present them to the user based on their input. The interaction involv ...

What could be the issue with injecting form information into a MySQL database with Node.js?

Currently, I am developing a web application for my school which requires me to create a login and register page. To achieve this, I have chosen to utilize node.js, express, and mysql. As I am still relatively new to node.js, I encountered an issue while t ...

Is there a way to bypass the "Error: Another application is currently displaying over Chrome" message using Javascript or Typescript?

Can the "Another app is displaying over chrome error" be bypassed using JavaScript or TypeScript? Error Message: https://i.stack.imgur.com/iSEuk.png ...

Is it possible to embed a Microsoft Teams meeting within an Iframe?

Is it possible for MS Teams to provide a URL of a video meeting that can be embedded in external locations, such as an iframe on my website? I attempted to add it like this: <iframe src="https://teams.microsoft.com/l/meetup-join/19%3ameeting_N2E3M ...

Inaccurate data is being shown by the Ajax method

I have a question that I haven't been able to find a satisfactory answer for: Recently, I started learning about AJAX methods and I'm trying to post some information processed by a php page named page.php. In my HTML file, I've included th ...