Looking for assistance with using an array in a for loop with an if-

I'm having trouble with a For loop array. I need to retrieve the data that is opposite of a given function, but when I use arr[i] != elem, it prints out the entire array. On the other hand, if I use arr[i] == elem, it gives me the array that I don't want. I still can't figure out why it's not working with != (not equal).

function getOppositeArray(arr, elem) {
let newArr = [];
// change code below this line
for(let i = arr.length -1; i >= 0 ; i--) {
  for(let j = arr[i].length-1;j >= 0;j--) {
    if(arr[i][j] !== elem) {
        newArr.push(arr[i]);
     }
   }
 }
 // change code above this line
  return newArr;
}

console.log(getOppositeArray([ ["trumpets", 2], ["flutes", 4], ["saxophones", 2] ], 2));

The desired result is ["flutes", 4]. I apologize if this question has been asked before. I have searched for an answer on Google but couldn't find one.

Thank you in advance for your assistance!

Answer №1

Great effort, you were very close!

You had a good approach by checking each value in the array individually. For example: 2 !== "trumpets" and 2 !== 2. This caused all arrays to be pushed because they all contained a string value that would never match.

To improve your code, consider removing the second loop and explicitly checking for the second value of the inner array:

function filteredArray(arr, elem) {
let newArr = [];
// update code below this line
for(let i = arr.length -1; i >= 0 ; i--) {
    if(arr[i][1] !== elem) {
        newArr.push(arr[i]);
     }
 }
 // update code above this line
  return newArr;
}

console.log(filteredArray([ ["trumpets", 2], ["flutes", 4], ["saxophones", 2] ], 2));

The above snippet highlights the flaw in your current method but does not provide a very flexible function. To check if an array includes a specific value, it's best to utilize some of the built-in array methods:

function filteredArray(arr, elem) {
  return arr.filter(values => !values.includes(elem));
}

console.log(filteredArray([ ["trumpets", 2], ["flutes", 4], ["saxophones", 2] ], 2));

console.log(filteredArray([ ["amy", "beth", "sam"], ["dave", "sean", "peter"] ], "peter"));

Answer №2

function filteredArray(arr, elem) {
  var resultArray = arr.filter(function(item) {
    return item.indexOf(elem) == -1;
  });
  return resultArray[0]
}
console.log(
  filteredArray([["trumpets", 2], ["flutes", 4], ["saxophones", 2]], 2)
);
console.log(
  filteredArray([ ["amy", "beth", "sam"], ["dave", "sean", "peter"] ], "peter")
);

This function will fetch the first element in an array that does not match the provided parameter. To get all non-matching items, you can simply replace return resultArray[0] with return resultArray.

Let's consider an example:

filteredArray([["trumpets", 2], ["flutes", 4], ["saxophones", 5]], 2)

With return resultArray[0], the output will be ["flutes", 4]

But if we use return resultArray, it will return

[["flutes", 4], ["saxophones", 5]]

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

Having trouble getting the jQuery script to properly check file size in an HTML form before uploading?

I've created an HTML form with a jQuery script to verify the file size when the SAVE button is clicked. Despite my efforts, the check doesn't seem to be functioning properly in the HTML Form. Please assist me with this and thank you in advance ...

Adjust the transparency of a separate image within a different container by hovering over another image container

Is my goal too complex to achieve? I am attempting to create a hover effect where the opacity of artwork1 and button1 changes simultaneously when hovered over. However, I am having trouble properly labeling my elements and getting them to interact as inten ...

Display two images consecutively within a single img tag

My goal is to display two images using a single <img /> tag. The first small image will be loaded and shown using the src attribute, while the second large image will be contained within the data-src attribute. Only one image will be displayed at a t ...

JavaScript Array Problem

Could you please review the code below and help me understand why I am encountering issues when trying to run the program? $(document).ready(function() { var comp = new Array("AAPL", "MSFT", "XRTX&"); var t = setInterval(function(){ ...

redux reducer returns an empty array after applying filter to the state

In my React component, I am utilizing Redux to manage the state. Since I am new to Redux, I have encountered some challenges with one of the reducers I created. One of the methods in my component involves making an HTTP request and then dispatching the dat ...

Display a webpage once its design is completely loaded in Nuxt

I have implemented a layout for my admin pages that displays user information in a consistent format, eliminating the need to fetch this data every time the page reloads. However, I am facing an issue where the page does not wait for the layout to fully l ...

Angular Date of Birth Verification

I'm new to Angular and struggling with date handling. I have a form that includes fields for the user's name and their date of birth. Before submitting the form, I need to validate that the person is over 18 years old and display an error messag ...

Collaborating on user authorization within a MEAN.JS framework

Recently, I decided to dive into the world of web application development by using MEAN.js full stack solution. Using the generators within MEAN.js, I was able to effortlessly create multiple CRUD models along with all the necessary express routes. In ad ...

Trigger the D3 component to re-render in React after a state change occurs in the parent component

My React project consists of two components written in TypeScript. The first component contains menus, and I am using conditional rendering to display different content based on user selection. <Menu.Item name="graph" active={activeItem ...

"Exploring the power of Vue.js through dynamic and recursive components

I am struggling with creating a recursive custom component that calls itself. Unfortunately, I keep encountering an error. An unknown custom element: <TestRec> - have you registered the component correctly? For recursive components, ensure to specif ...

Issues with Laravel 8's datatable scripts causing dysfunction

In my practice with the AdminBSB template, I am facing an issue where the Jquery datatable plugin JS is not functioning properly in my blade template. I aim to achieve a datatable layout similar to this example: https://i.sstatic.net/krfPl.jpg However, t ...

Looking for assistance in setting up a personalized slideshow to automatically play on its

Recently, I have taken responsibility for a project that was initiated by someone else. The website contains a customized slideshow on its homepage. To meet the client's requirements, I have already made some alterations to the appearance and feel of ...

Showing no background color until the user lifts their finger

I am currently in the process of developing a website. The navigation on the website starts off as transparent (background: transparent) when opened, but as soon as you start scrolling, it should transition to a colorful state with shades like grey, midnig ...

Obtain an oAuth token through the use of npm

Recently, I've been working on a nodeJS service to fetch an OAuth token from a server. Unfortunately, I keep encountering errors when running the function below: var express = require('express') var http = require('http'); var htt ...

Retrieve the value of a duplicated object key from a JSON and replace it with just one unique value

In my current project, I am faced with the challenge of extracting duplicate object keys' values from a JSON dataset and replacing them with only one value. My goal is to ultimately return these unique key-value pairs as an array. NOTE: This data has ...

nodejs promises and their implementation in loops

Currently delving into the realm of promises in nodejs, here's an example code snippet for you to peruse: The result when running the below code is as follows: test - 1 test - 2 test - 3 test - 4 var Q = require('q'); var promise = Q.when( ...

AngularJS Service failing to appear on screen

I am trying to access my Github information using Github's API. I can see the correct information when I log my http request, but for some reason it is not showing up on the page. There are no errors being thrown, but the requested data is not display ...

What could be the reason for v-model not functioning properly?

Embarking on my Vue.js coding journey, I am currently following a straightforward online tutorial. Utilizing the vue-cli, I kickstarted my application and crafted a basic component named Test.vue. Within this component lies a simplistic input control conne ...

jQuery Animation: Creative Menu Icon Display

Whenever the toggle menu's navigation icon is clicked, it triggers an animation that transforms the "hamburger" icon into an "X", causing the navigation menu to drop down. If a user clicks either the navigation icon or outside of the active toggle me ...

The embedded iframe on YouTube is displaying the incorrect video

I am currently designing a website and I want to feature a video on the homepage. The video is hosted on YouTube and I need to embed it into my website. <html> <iframe width="560" height="315" src="https://www.youtube.com/embed/spPdelVEs_k?rel= ...