Eliminate any uneven values within the array

I'm in search of a different approach to eliminate all odd numbers from an array. A friend proposed this solution which I understand, but I have yet to think of another method. Do you have any thoughts on how to tackle this differently?

Javascript

let myArray = [1,3,5,7,9,2,4,6,8];
let length = myArray.length;

for(let i = 0; i < length; i++) {
    for(let j = 0; j < myArray.length; j++) {
        if(myArray[j] % 2 === 1) {
            myArray.splice(j, 1);
            break;
        }
    }
};

console.log(myArray);

Answer №1

const numbers = [2, 4, 6, 8, 10, 1, 3, 5, 7, 9];

const evenNumbers = numbers.filter(num => num % 2 === 0);

console.log(evenNumbers);

Answer №2

Your inquiry is focused on the process of "removing odds" rather than retaining evens. While the end result remains unchanged, there are various approaches to achieving this outcome. Not every scenario will have a clear-cut opposite function that can be directly applied with Array.prototype.filter. As a result, the solutions provided here will concentrate on eliminating elements based on the identification of odd values, as opposed to preserving even elements. In the following section, diverse strategies will be outlined to address your issue before delving into an evaluation of your existing code.

Insight from Your Friend:

I've included a console.log statement within your inner loop to facilitate visualization of each element being assessed. It's apparent that the current solution involves more computational effort than necessary - utilizing multiple loops to iterate through the array of numbers. One loop should suffice for traversing the array efficiently.

Additionally, it's imperative to exercise caution when altering the length of an array while iterating over it. For instance, employing arr.splice(i,1) results in certain consequences during iteration:

  • All elements to the right of "i" shift left by one position.
  • The overall length of the array diminishes by one.

Considering these outcomes, how should the loop adapt accordingly?

  • If all elements shift left after a splice operation, we must reevaluate the same index i once more since it now corresponds to a new value.
  • Given the reduction in length by one, adjustments in the loop’s exit condition are necessary to conclude one iteration earlier.

The response titled mutRejectOdds subsequently tackles these specific concerns.


Recursive Approach:

Boasting high readability and simplicity, yet not immune to stack overflow risks.

const isOdd = x => x % 2 !== 0;

const removeOdds = ([x,...xs]) => {
  if (x === undefined)
    return [];
  else if (isOdd(x))
    return removeOdds(xs);
  else
    return [x, ...removeOdds(xs)];
}

let data = [1,2,3,4,5,6,7,8];
console.log(removeOdds(data)); // [2,4,6,8]
console.log(data);             // [1,2,3,4,5,6,7,8]


Linear Iterative Method using Accumulator:

An approach that ensures stack safety and practical utility.

const isOdd = x => x % 2 !== 0;

const removeOdds = xs => {
  let acc = [];
  for (let x of xs) {
    if (!isOdd(x)) {
      acc.push(x);
    }
  }
  return acc;
}

let data = [1,2,3,4,5,6,7,8];
console.log(removeOdds(data)); // [2,4,6,8]
console.log(data);             // [1,2,3,4,5,6,7,8]


Continuation Passing Style Technique:

An intricate recursive solution that could benefit from trampolining for enhanced stack safety.

const isOdd = x => x % 2 !== 0;

const identity = x => x;

const removeOdds = xs => {
  const aux = ([x,...xs], k) => {
    if (x === undefined)
      return k([]);
    else if (isOdd(x))
      return aux(xs, k);
    else
      return aux(xs, acc => k([x, ...acc]));
  };
  return aux(xs, identity);
}

let data = [1,2,3,4,5,6,7,8];
console.log(removeOdds(data)); // [2,4,6,8]
console.log(data);             // [1,2,3,4,5,6,7,8]


Higher-Order Function Implementation:

Similar to the recursive methodology, but incorporating an extra argument representing a function identifying elements to skip - amenable to linear iterative or continuation passing style implementation.

const isOdd = x => x % 2 !== 0;

const reject = (f, [x,...xs]) => {
  if (x === undefined)
    return [];
  else if (f(x))
    return reject(f, xs);
  else
    return [x, ...reject(f, xs)];
}

let data = [1,2,3,4,5,6,7,8];
console.log(reject(isOdd, data)); // [2,4,6,8]
console.log(data);                // [1,2,3,4,5,6,7,8]


Function Composition with Array.prototype.filter:

A pragmatic utilization of the built-in Array.prototype.filter, reversing the output via function composition involving not.

const isOdd = x => x % 2 !== 0;

const comp = f => g => x => f(g(x));

const not = x => !x;

const reject = (f, xs) =>
  xs.filter(comp(not)(f));

let data = [1,2,3,4,5,6,7,8];
console.log(reject(isOdd, data)); // [2,4,6,8]
console.log(data);                // [1,2,3,4,5,6,7,8]


In-Place Mutation via Linear Iteration:

All foregoing methods avoid mutating the original data. However, under specific circumstances where creating a copy devoid of odd values is unnecessary, direct modification to data may be preferred.

This proposed solution rectifies the issues inherent in your initial code snippet.

const isOdd = x => x % 2 !== 0;

const mutRejectOdds = xs => {
  for (let i = 0, len = xs.length; i < len; i++) {
    if (isOdd(xs[i])) {
      xs.splice(i, 1);
      i--;
      len--;
    }
  }
}

let data = [1,2,3,4,5,6,7,8];
console.log(mutRejectOdds(data)); // undefined
console.log(data);                // [2,4,6,8]

Answer №3

If your browser support goes back only as far as IE9, then the Array.prototype.filter method is a suitable option to use.

let numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

let evenNumbers = numbers.filter(function(num) {
    return num % 2 === 0;
});

The output will be a new array containing only the filtered values (in this case, only even numbers).

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

Incorporate additional items into the current array

My current array has the following structure: array(3) { [0]=> array(4) { ["sort"]=> string(0) "" ["day"]=> string(2) "2" ["month"]=> string(1) "8" ["year"]=> strin ...

typescript throw error: declaration or statement should be exported as an object

Could you clarify why this code functions correctly in TypeScript when exporting an object: export const settings = { port: 4000 }; Another way that works is: const settings = { port: 4000 }; export { settings }; However, this example result ...

What are some strategies for getting neglected distribution files onto Bower despite being ignored by git?

I am in the process of creating a package for NPM and Bower. To maintain organization, I store my working files (ES6) in the src/ directory of the package and compile the distribution files (ES5, using Babel) in the lib/ directory. For version control, I ...

React component for performing lenient string comparisons

I am in the process of creating a quiz and I am interested in exploring how I can compare a user's answers to a set of correct responses. Currently, I assess the user's score by using the strict === operator to verify an exact match between their ...

Creating and utilizing multi-module NPM packages written in Typescript: A comprehensive guide

For a while now, I've been quite at ease creating and utilizing NPM packages with Typescript. However, these packages have typically been provided and consumed as a single module. Now, I'm interested in publishing packages that contain more than ...

Employing eval for parsing the JSON data

function ajaxFunction(){ var ajaxRequest; // The variable that enables the use of Ajax technology! try{ // Compatible with Opera 8.0+, Firefox, and Safari ajaxRequest = new XMLHttpRequest(); } catch (e){ // For Internet Explorer Browsers ...

I am attempting to code a program but it keeps displaying errors

What is hierarchical inheritance in AngularJS? I have been attempting to implement it, but I keep encountering errors. import {SecondcomponentComponent} from './secondcomponent/secondcomponent.Component'; import {thirdcomponentcomponent} from & ...

Retrieving information from React elements

Recently, I ventured into the world of React and started building a mock website for online food ordering. One of my components is called Items, which utilizes props to display all the food items on the webpage. import { useState } from "react"; ...

What is the best way to calculate the average of values from multiple objects sharing the same key in an array using JavaScript?

Consider an array with student profiles: let profile = [ {student: "A", english: 80, maths: 80}, {student: "A", english: 70, maths: 60}, {student: "B", english: 50, maths: 50}, {student: "B", english: "--", ...

List output with jQuery AJAX showing object data

Here is my code that utilizes ajax for searching: $("#keyword").keyup(function() { var keyword = $("#keyword").val(); if (keyword.length >= MIN_LENGTH) { $.get( "./lib/data_siswa_ajax.php", { keyword: keyword, sekolah: $("#sekolah").val ...

Converting object's date property to a new Date() in TypeScript

I am working with a CurrentWeather Model retrieved from localStorage and parsed into an object. export interface CurrentWeather { LocalObservationDateTime: Date; Latitude: string; Longitude: string; LocationKey: string; LocalizedName: s ...

What is the best way to incorporate a <li> view cap within a div element using JavaScript?

Currently, I am attempting to implement a dynamic <li> view limit within the content of a div. My goal is to display only 3 <li> elements each time the div content is scrolled. Although not confirmed, I believe this example may be helpful: ...

Debugger pause following Meteor.call, maybe client/server debugging

Having trouble debugging a Meteor method on the server side. While debugging in the client (using Chrome), the debugger progresses until the 4th line of code ("Meteor.call") and then immediately jumps back to the 2nd line ("convlist:function()"), skipping ...

What is the best way to store multiple arrays within an array in Python?

My goal is to create a 5x5 array in Python that will store a total of 25 arrays. Currently, I am attempting to divide an image into 25 pieces using nested loops in openCV. However, I am struggling with saving the cropped images in the slices array. board = ...

"Incorporating Adobe Edge Animate alongside AngularJS and AngularUI Router for dynamic web design

Currently, I'm in the process of integrating multiple animations created using Adobe Edge Animate into a single AngularJS application for a project. These animations will serve as the visual elements for a game, with player input controlling the compo ...

What is the preferred method for front-end and back-end communication regarding the linking of notification routes?

Looking to integrate a react application with real-time notifications that may contain links to different routes within the app. How can the backend be informed about these routes? What communication method should be used? One possible approach is to cate ...

Building an Ionic Angular application that converts milliseconds to DateTime values retrieved from local storage

I have a mobile app built using Ionic framework where I retrieve data from local storage. My goal is to convert the milliseconds into a readable date format. I have tried the code below but it's not giving me the desired output. Can you please point ...

Using Node.js and Express to import a simple JavaScript file as a router

Can anyone help me understand how to import the user.json json file into my user.js? I want the json file to be displayed when typing /user but I'm struggling with the new version of Node. index.js import express from 'express'; import body ...

Remove multiselect label in PrimeNG

I am attempting to change the multiselect label of selected items and replace it with a static default label. Here is what it currently shows: https://i.sstatic.net/qBNHG.png This is what I have tried: .p-multiselect-label { visibility: collapse; ...

Retrieve the overall number of Formik errors for a specific field array

In the given Yup validation setup below, there is a nested Formik FieldArray: parentLevel: Yup.array().of( Yup.object({ childrenLevel: Yup.array().of( Yup.object({ childName: Yup.string().required('Name is required') ...