Manipulating the content of an array based on a specific key value using JavaScript's

Looking for a way to utilize a multidimensional array fruits in my code. The goal is to splice and push the values from the suggestFruits array into either the red or green fruits array based on the type specified. For example, items with type:1 should go to the "Red Fruits" table, while items with type:2 should go to the "Green Fruits" table. Any suggestions on how to achieve this would be highly appreciated!


                var red = {};
                var green = {};
                var random = {};
                var fruits = [];

                var fruits1 = {["fruit"]:"Apple", ["type"]:"1"}
                var fruits2 = {["fruit"]:"Tomato", ["type"]:"1"}
                var fruits3 = {["fruit"]:"Lime", ["type"]:"2"}
                var fruits4 = {["fruit"]:"Guava", ["type"]:"2"}

                // Add fruits to main array
                fruits.push(fruits1,fruits2,fruits3,fruits4);
                console.log(fruits);

                // Filter suggestFruits
                var suggestFruits = fruits.filter(x => x.fruit).map(x => x.fruit);
                console.log(suggestFruits);

                // Initial fruit arrays
                var key = "Red Fruits";
                red[key] = ['Apple', 'Cherry', 'Strawberry','Pomegranate','Raspberry'];

                var key2 = "Green Fruits";
                green[key2] = ['Watermelon', 'Durian', 'Avocado','Lime', 'Honeydew'];

                var key3 = "Random Fruits";
                random[key3] = suggestFruits;

                function redraw() {
                    // Redraw fruit displays
                }

                function listener() {
                    // Event listeners for clicking fruits
                }
            

                .pilldiv {
                  padding: 8px 15px;
                  text-align: center;
                  font-size: 15px;
                  border-radius: 25px;
                  color: Black;
                  margin: 2px;
                }
            

                <!DOCTYPE html>
                <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
                <html>
                <head>
                    ...
                </body>
                </html>
            

Answer №1

There is quite a bit to unpack in this query, but it seems like your objective is straightforward: move fruits with type === "1" to the red fruits array, and fruits with type === "2" to the green fruits array.

The key issue you are facing with categorizing the suggestedFruits into red and green groups is that the type information gets lost when creating the suggestedFruits array. To address this, you can refer back to the original fruits array to retain the information.

Here's an approach to achieve this:

var fruits = [
  {fruit:"Apple", type:"1"},
  {fruit:"Tomato", type:"1"},
  {fruit:"Lime", type:"2"},
  {fruit:"Guava", type:"2"},
];
// create a mapping for fruit types
var fruitTypeMap = {"1": "Red Fruits", "2": "Green Fruits"}
// container for different fruit types
var fruitTypes = {
  "Red Fruits": ['Apple', 'Cherry', 'Strawberry','Pomegranate','Rassberry'],
  "Green Fruits": ['Watermelon', 'Durian', 'Avacado','Lime','Honeydew'],
  "Random Fruits": fruits.map(fruit => fruit.fruit)
};
// clone element for easy creation of fruit-pills
var clonePill = $(".clone");
// initialize the red/green/random pills
Object.keys(fruitTypes).forEach(key => {
  fruitTypes[key].forEach(fruit => {
    var $newFruit = clonePill.clone();
    // remove clone class for visibility and avoid re-cloning
    $newFruit.removeClass("clone");
    // set the text
    $newFruit.text(fruit);
    // append to the correct list in DOM
    $(`[data-fruits="${key}"]`).append($newFruit);
  });
});

// function to handle moving fruits between categories
function moveFruit (e) {
  // get the category from data-fruits property on parent container
  var fruitCategory = $(this).parent().data("fruits");
  var fruitName = $(this).text();
  // detach the fruit element from DOM and store it temporarily
  var $fruit = $(this).detach();
  if (fruitCategory === "Random Fruits") {
    // get the type number from the original fruits array
    var fruitType = fruits.find(fruit => fruit.fruit === fruitName).type;
    // find the correct array for the fruit
    var fruitArr = fruitTypes[fruitTypeMap[fruitType]];
    // index of the fruit in current array
    var fruitIndex = fruitTypes["Random Fruits"].indexOf(fruitName);
    // splice out from current array and insert into destination array
    fruitArr.push(fruitTypes["Random Fruits"].splice(fruitIndex, 1)[0]);
    // add movable class for toggling back to Random Fruits
    $fruit.addClass("movable");
    // add to the correct list in the DOM
    $(`[data-fruits="${fruitTypeMap[fruitType]}"]`).append($fruit); 
  }
  else {
    var fruitArr = fruitTypes[fruitCategory];
    var fruitIndex = fruitArr.indexOf(fruitName);
    fruitTypes["Random Fruits"].push(fruitArr.splice(fruitIndex, 1)[0]);
    $('[data-fruits="Random Fruits"]').append($fruit); 
  }
}
$(".red-fruits, .green-fruits").on("click", ".movable", moveFruit);
$(".random-fruits").on("click", ".fruit-pill", moveFruit);
.clone {
  display: none;
}
.fruit-pill {
  border-radius: 20px;
  padding: 10px 15px;
  display: inline-block;
}
.movable {
  cursor: pointer;
}
.red-fruits > .fruit-pill {
  background-color: rgba(255, 0, 0, 0.6);
}
.red-fruits > .movable {
  background-color: rgb(255, 150, 150);
}
.green-fruits > .fruit-pill {
  background-color: rgba(0, 255, 0, 0.7);
}
.green-fruits > .movable {
  background-color: rgb(200, 255, 175);
}
.random-fruits > .fruit-pill {
  background-color: rgba(0, 0, 0, 0.2);
  cursor: pointer;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="fruits-container">
  <div class="red-fruits" data-fruits="Red Fruits">
  </div>
  <div class="green-fruits" data-fruits="Green Fruits">
  </div>
  <div class="random-fruits" data-fruits="Random Fruits">
  </div>
</div>
<div class="fruit-pill clone"></div>

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

Is there a way to modify the state following a sorting operation?

How can I properly update the state after sorting by salary? state = { workers: [ {name: 'Bob', surname: 'Meljanski', salary: 5140}, {name: 'Michel', surname: 'Hensson', salary: 5420}, {n ...

Unable to establish a connection between two localhost servers

I'm encountering an issue with my API and React application setup. The API is running on localhost:3001, while the React app is on localhost:3000. Despite being able to make requests using Postman, I keep getting blocked by CORS policy when trying to ...

Creating custom shaders for YouTube videos within a Three.js userscript

I want to add a shader effect to YouTube videos. My current approach involves using Three.js to implement a shader on a video. Specifically, I am trying to adapt this example of applying a shader to a video (code available here) into a Tampermonkey usersc ...

utilizing the active class with react js

Apologies for the question, but I am facing an issue where adding an active class to a button is affecting all buttons when clicked. How can this be fixed? Here is the code snippet: <div className=""> {category.items.length === 0 ? ( ...

What steps should I follow to make a brief .mp3 audio file play with each keystroke?

I'm in the process of developing a web application with a form, and I want to incorporate a keypress sound effect as a progressive enhancement for better user experience. The sound effect I have chosen is quite short (0.18s). However, when testing m ...

Tips on automatically centering an image within a div as it is resized

I'm currently working on a website that showcases cards featuring Discord users. Each card includes an avatar image within a div element, and when the user hovers over it, the image expands. However, I've noticed that as it expands, it shifts to ...

Verify whether a component is a React.ReactElement<any> instance within a child mapping operation

I am facing a challenge with a component that loops through children and wraps them in a div. I want to exclude certain elements from this process, but I am struggling to determine if the child is a ReactElement or not (React.ReactChild can be a string or ...

I possess three stylish CSS buttons, however, the other one is accompanied by <br />

I'm struggling to ensure that the three CSS buttons are the same size (using padding) and vertically aligned, as the second button includes a "<br />" which throws off the alignment. I was advised to use flexbox, but I haven't been able to ...

tips for organizing the <div> element horizontally within a design

I have reviewed some similar questions that have been posted and attempted to apply their solutions to my code. However, I am still encountering difficulties. Below is the code that I need help with. I am looking to organize the main content along with t ...

Is it obligatory to reply with status code 200 in Express?

Is it required to explicitly include a status 200 code in the response or is it set automatically? response.json({ status: 'OK', }); vs. response .status(200) .json({ status: 'OK', }); Upon testing the route in my browser, ...

Unraveling a JSON array in PHP

Having trouble decoding a JSON object in PHP that is received from a JavaScript page? Here's how you can decode the JSON and store it in PHP such that $arr[0]=[1,2,34,5,2]; $arr[1]=[2,1,34,5,2]; $arr[2]=[8,1,34,5,2]; in PHP. after removing "myString ...

Troubleshooting the Ui-router refresh problem

I set up my ui-router configuration as follows: app.config(function($stateProvider, $urlRouterProvider, $locationProvider) { $stateProvider .state('home', { url: "/home", templateUrl : 'h ...

Update: "Mui V5 - Eliminate collapse/expand icons in TreeView and reduce TreeItem indentation"

My current project involves Mui V5 and I am looking to customize the TreeView component. Specifically, I need to remove the collapse/expand icons as I want them to be integrated into the TreeItem label component on the left side instead of the right. Add ...

Delivering a static Angular app through an Express Server

In my current setup, I have an Angular app being served as static content in an Express Server. When Express serves static files, it automatically adds an ETag to them. Subsequent requests will then check if the ETag matches before sending the files agai ...

Show a specific div element from an external webpage within an iframe

Is it possible to showcase the content of a specific div with the ID="example" from an external page within an iframe on my website? I do not have any authority over the external page, only on my own site. The sole information I possess from that externa ...

How to fix the issue of a static background image in Bootstrap that does not

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <!--Bootstrap--& ...

Tap on the child to reveal their parent

I am working with a family tree that includes dropdown menus containing the names of parents and children. Each child has a link, and when I click on a child's link, I want their father to be displayed in the dropdown menu as the selected option. Can ...

What is the best method to merge duplicate arrays based on their values using PHP?

Consider the following example array: $myArr1 = array( "word1" => "hello", "word2" => "hi", "word3" => "welcome", ); $myArr2 = array( "word1" => "hello", "word3" => "welcome", "word2" => "hola" ); Is there a way to combine duplicate ke ...

Executing the countdown function within the catch/error block of $http.post does not work as expected in Vue.js

I encountered an issue with a simple code snippet that involves calling a countdown timer within the catch function of $http.post. this.$http.post('/api/task/post', updatedTask ,function(data){ alert('success!') }).catch( ...

Continuously encountering IndexErrors while attempting to manipulate char arrays

Currently in the midst of a simulation project, I have a piece of code that organizes data into an array in a particular way: [['_' '_' 'F' '_' '_'] ['_' '_' '_' '_&apos ...